Conditions | 12 |
Total Lines | 94 |
Code Lines | 44 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like oidc.*Authn.Authenticate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | package oidc |
||
83 | func (oidc *Authn) Authenticate(requestContext context.Context) error { |
||
84 | // Extract the authorization header from the metadata of the incoming gRPC request. |
||
85 | authHeader, err := grpcauth.AuthFromMD(requestContext, "Bearer") |
||
86 | if err != nil { |
||
87 | // Log the error if the authorization header is missing or does not start with "Bearer" |
||
88 | slog.Error("failed to extract authorization header from gRPC request", "error", err) |
||
89 | // Return an error indicating the missing or incorrect bearer token |
||
90 | return errors.New(base.ErrorCode_ERROR_CODE_MISSING_BEARER_TOKEN.String()) |
||
91 | } |
||
92 | |||
93 | // Log the successful extraction of the authorization header for debugging purposes. |
||
94 | // Remember, do not log the actual content of authHeader as it might contain sensitive information. |
||
95 | slog.Debug("Successfully extracted authorization header from gRPC request") |
||
96 | |||
97 | // Parse and validate the JWT token extracted from the authorization header. |
||
98 | parsedToken, err := oidc.jwtParser.Parse(authHeader, func(token *jwt.Token) (interface{}, error) { |
||
99 | slog.Info("starting JWT parsing and validation.") |
||
100 | |||
101 | // Fetch the public keys from the JWKS endpoint configured for the OIDC. |
||
102 | jwks, err := oidc.jwksSet.Fetch(requestContext, oidc.JwksURI) |
||
103 | if err != nil { |
||
104 | slog.Error("failed to fetch JWKS", "uri", oidc.JwksURI, "error", err) |
||
105 | // If fetching the JWKS fails, return an error. |
||
106 | return nil, fmt.Errorf("failed to fetch JWKS: %w", err) |
||
107 | } |
||
108 | |||
109 | slog.Debug("successfully fetched JWKS", "jwks", jwks) |
||
110 | |||
111 | // Retrieve the key ID from the JWT header and find the corresponding key in the JWKS. |
||
112 | if keyID, ok := token.Header["kid"].(string); ok { |
||
113 | slog.Debug("attempting to find key in JWKS", "kid", keyID) |
||
114 | |||
115 | if key, found := jwks.LookupKeyID(keyID); found { |
||
116 | // If the key is found, convert it to a usable format. |
||
117 | var k interface{} |
||
118 | if err := key.Raw(&k); err != nil { |
||
119 | slog.Error("failed to get raw public key", "kid", keyID, "error", err) |
||
120 | return nil, fmt.Errorf("failed to get raw public key: %w", err) |
||
121 | } |
||
122 | slog.Debug("successfully obtained raw public key", "key", k) |
||
123 | return k, nil // Return the public key for JWT signature verification. |
||
124 | } |
||
125 | slog.Error("key ID not found in JWKS", "kid", keyID) |
||
126 | // If the specified key ID is not found in the JWKS, return an error. |
||
127 | return nil, fmt.Errorf("kid %s not found", keyID) |
||
128 | } |
||
129 | slog.Error("jwt does not contain a key ID") |
||
130 | // If the JWT does not contain a key ID, return an error. |
||
131 | return nil, errors.New("kid must be specified in the token header") |
||
132 | }) |
||
133 | if err != nil { |
||
134 | // Log that the token parsing or validation failed |
||
135 | slog.Error("token parsing or validation failed", "error", err) |
||
136 | // If token parsing or validation fails, return an error indicating the token is invalid. |
||
137 | return errors.New(base.ErrorCode_ERROR_CODE_INVALID_BEARER_TOKEN.String()) |
||
138 | } |
||
139 | |||
140 | // Ensure the token is valid. |
||
141 | if !parsedToken.Valid { |
||
142 | // Log that the parsed token was not valid |
||
143 | slog.Warn("parsed token is invalid") |
||
144 | // Return an error indicating the invalid token |
||
145 | return errors.New(base.ErrorCode_ERROR_CODE_INVALID_BEARER_TOKEN.String()) |
||
146 | } |
||
147 | |||
148 | // Extract the claims from the token. |
||
149 | claims, ok := parsedToken.Claims.(jwt.MapClaims) |
||
150 | if !ok { |
||
151 | // Log that the claims were in an incorrect format |
||
152 | slog.Warn("token claims are in an incorrect format") |
||
153 | // Return an error |
||
154 | return errors.New(base.ErrorCode_ERROR_CODE_INVALID_CLAIMS.String()) |
||
155 | } |
||
156 | |||
157 | slog.Debug("extracted token claims", "claims", claims) |
||
158 | |||
159 | // Verify the issuer of the token matches the expected issuer. |
||
160 | if ok := claims.VerifyIssuer(oidc.IssuerURL, true); !ok { |
||
161 | // Log that the issuer did not match the expected issuer |
||
162 | slog.Warn("token issuer is invalid", "expected", oidc.IssuerURL, "actual", claims["iss"]) |
||
163 | // Return an error |
||
164 | return errors.New(base.ErrorCode_ERROR_CODE_INVALID_ISSUER.String()) |
||
165 | } |
||
166 | |||
167 | // Verify the audience of the token matches the expected audience. |
||
168 | if ok := claims.VerifyAudience(oidc.Audience, true); !ok { |
||
169 | // Log that the audience did not match the expected audience |
||
170 | slog.Warn("token audience is invalid", "expected", oidc.Audience, "actual", claims["aud"]) |
||
171 | // Return an error |
||
172 | return errors.New(base.ErrorCode_ERROR_CODE_INVALID_AUDIENCE.String()) |
||
173 | } |
||
174 | |||
175 | // If all validations pass, return nil indicating the token is valid. |
||
176 | return nil |
||
177 | } |
||
295 |