Compare commits

..

No commits in common. "main" and "0.4.6" have entirely different histories.
main ... 0.4.6

3 changed files with 21 additions and 50 deletions

View File

@ -1,6 +1,6 @@
# Package # Package
version = "0.4.7" version = "0.4.6"
author = "Jonathan Bernard" author = "Jonathan Bernard"
description = "Jonathan's opinionated extensions and auth layer for Jester." description = "Jonathan's opinionated extensions and auth layer for Jester."
license = "MIT" license = "MIT"

View File

@ -1,2 +1,5 @@
import buffoonery/[apierror, apiutils, auth, jsonutils] import buffoonery/apierror,
buffoonery/apiutils,
buffoonery/auth,
buffoonery/jsonutils
export apierror, apiutils, auth, jsonutils export apierror, apiutils, auth, jsonutils

View File

@ -4,14 +4,13 @@ import std/httpclient except HttpHeaders
import jwt_full, jwt_full/encoding import jwt_full, jwt_full/encoding
import ./[apiutils,jsonutils] import ./apiutils, ./jsonutils
const SUPPORTED_SIGNATURE_ALGORITHMS = @[ HS256, RS256 ] const SUPPORTED_SIGNATURE_ALGORITHMS = @[ HS256, RS256 ]
type type
AuthError* = object of CatchableError AuthError* = object of CatchableError
additionalInfo*: Option[TableRef[string, JsonNode]]
ApiAuthContext* = ref object ApiAuthContext* = ref object
appDomain*: string ## Application domain for session cookies appDomain*: string ## Application domain for session cookies
@ -29,19 +28,6 @@ type
issuerKeys: TableRef[string, JwkSet] issuerKeys: TableRef[string, JwkSet]
proc failAuth*[T](
reason: string,
additionalInfo: TableRef[string, T],
parentException: ref Exception = nil) =
## Syntactic sugar to raise an AuthError. Reason will be the exception
## message and should be considered an internal message.
let err = newException(AuthError, reason, parentException)
err.additionalInfo = some(newTable[string, JsonNode]())
for key, val in additionalInfo.pairs:
err.additionalInfo.get[key] = %val
raise err
proc failAuth*(reason: string, parentException: ref Exception = nil) = proc failAuth*(reason: string, parentException: ref Exception = nil) =
## Syntactic sugar to raise an AuthError. Reason will be the exception ## Syntactic sugar to raise an AuthError. Reason will be the exception
## message and should be considered an internal message. ## message and should be considered an internal message.
@ -77,7 +63,6 @@ proc initApiAuthContext*(
proc fetchJWKs(openIdConfigUrl: string): JwkSet {.gcsafe.} = proc fetchJWKs(openIdConfigUrl: string): JwkSet {.gcsafe.} =
## Fetch signing keys for an OAuth issuer. `openIdConfigUrl` is expected to ## Fetch signing keys for an OAuth issuer. `openIdConfigUrl` is expected to
## be a well-known URL (ISSUER_BASE/.well-known/openid-configuration) ## be a well-known URL (ISSUER_BASE/.well-known/openid-configuration)
var jwksKeysURI: string
try: try:
let http = newHttpClient() let http = newHttpClient()
@ -85,20 +70,14 @@ proc fetchJWKs(openIdConfigUrl: string): JwkSet {.gcsafe.} =
let metadata = parseJson(http.getContent(openIdConfigUrl)) let metadata = parseJson(http.getContent(openIdConfigUrl))
# Fetch the keys from the jwk_keys URI. # Fetch the keys from the jwk_keys URI.
jwksKeysURI = metadata.getOrFail("jwks_uri").getStr let jwksKeysURI = metadata.getOrFail("jwks_uri").getStr
let jwksKeys = parseJson(http.getContent(jwksKeysURI)) let jwksKeys = parseJson(http.getContent(jwksKeysURI))
# Parse and load the keys provided. # Parse and load the keys provided.
return initJwkSet(jwksKeys) return initJwkSet(jwksKeys)
except Exception: except:
#failAuth "unable to fetch isser signing keys" failAuth("unable to fetch isser signing keys", getCurrentException())
failAuth(
reason = "unable to fetch isser signing keys",
additionalInfo = newTable[string, string]({
"openIdConfigUrl": openIdConfigUrl,
"jwksKeysURI": jwksKeysURI }),
parentException = getCurrentException())
proc addSigningKeys*(ctx: ApiAuthContext, issuer: string, keySet: JwkSet): void = proc addSigningKeys*(ctx: ApiAuthContext, issuer: string, keySet: JwkSet): void =
@ -121,8 +100,8 @@ proc findSigningKey*(ctx: ApiAuthContext, jwt: JWT, allowFetch = true): JWK {.gc
## [OpenID Connect standard discovery mechanism](https://openid.net/specs/openid-connect-discovery-1_0.html) ## [OpenID Connect standard discovery mechanism](https://openid.net/specs/openid-connect-discovery-1_0.html)
try: try:
if jwt.claims.iss.isNone: failAuth "JWT is missing 'iss' claim." if jwt.claims.iss.isNone: failAuth "Missing 'iss' claim."
if jwt.header.kid.isNone: failAuth "JWT is missing 'kid' header." if jwt.header.kid.isNone: failAuth "Missing 'kid' header."
if ctx.issuerKeys.isNil: ctx.issuerKeys = newTable[string, JwkSet]() if ctx.issuerKeys.isNil: ctx.issuerKeys = newTable[string, JwkSet]()
@ -141,11 +120,7 @@ proc findSigningKey*(ctx: ApiAuthContext, jwt: JWT, allowFetch = true): JWK {.gc
fetchJWKs(jwtIssuer & "/.well-known/openid-configuration") fetchJWKs(jwtIssuer & "/.well-known/openid-configuration")
return ctx.findSigningKey(jwt, false) return ctx.findSigningKey(jwt, false)
failAuth( failAuth "unable to find JWT signing key"
reason = "unable to find JWT signing key",
additionalInfo = newTable[string, string]({
"jwtIssuer": jwtIssuer,
"jwtKid": jwt.header.kid.get}))
except: except:
failAuth("unable to find JWT signing key", getCurrentException()) failAuth("unable to find JWT signing key", getCurrentException())
@ -155,21 +130,18 @@ proc validateJWT*(ctx: ApiAuthContext, jwt: JWT) =
## Given a JWT, validate that it is a well-formed JWT, validate the issuer's ## Given a JWT, validate that it is a well-formed JWT, validate the issuer's
## signature on the token, and validate all the claims that it preesnts. ## signature on the token, and validate all the claims that it preesnts.
try: try:
if jwt.claims.iss.isNone: failAuth "JWT is missing 'iss' claim." if jwt.claims.iss.isNone: failAuth "Missing 'iss' claim."
let jwtIssuer = jwt.claims.iss.get let jwtIssuer = jwt.claims.iss.get
if not ctx.trustedIssuers.contains(jwtIssuer): if not ctx.trustedIssuers.contains(jwtIssuer):
failAuth( failAuth "JWT is issued by $# but we only trust $#" %
reason = "We don't trust the JWT's issuer.", [jwtIssuer, $ctx.trustedIssuers]
additionalInfo = newTable[string, JsonNode]({
"issuer": %jwtIssuer,
"trustedIssuers": %ctx.trustedIssuers}))
if jwt.header.alg.isNone: failAuth "JWT is missing 'alg' header property." if jwt.header.alg.isNone: failAuth "Missing 'alg' header property."
if jwt.claims.aud.isNone: failAuth "JWT is missing 'aud' claim." if jwt.claims.aud.isNone: failAuth "Missing 'aud' claim."
if jwt.claims.iss.isNone: failAuth "JWT is missing 'iss' claim." if jwt.claims.iss.isNone: failAuth "Missing 'iss' claim."
if jwt.claims.sub.isNone: failAuth "JWT is missing 'sub' claim." if jwt.claims.sub.isNone: failAuth "Missing 'sub' claim."
if jwt.claims.exp.isNone: failAuth "JWT is missing or invalid 'exp' claim." if jwt.claims.exp.isNone: failAuth "Missing or invalid 'exp' claim."
if jwt.claims["aud"].get.kind == JString: if jwt.claims["aud"].get.kind == JString:
# If the token is for a single audience, check that it is for us. # If the token is for a single audience, check that it is for us.
@ -254,11 +226,7 @@ proc extractValidJwt*(ctx: ApiAuthContext, req: Request, validateCsrf = true): J
failAuth "missing CSRF token" failAuth "missing CSRF token"
if req.headers["X-CSRF-TOKEN"] != result.claims["csrfToken"].get.getStr(""): if req.headers["X-CSRF-TOKEN"] != result.claims["csrfToken"].get.getStr(""):
failAuth( failAuth "invalid CSRF token"
reason = "invalid CSRF token",
additionalInfo = newTable[string, string]({
"header": req.headers["X-CSRF-TOKEN"],
"jwt": result.claims["csrfToken"].get.getStr("")}))
else: failAuth "no auth token, no Authorization or Cookie headers" else: failAuth "no auth token, no Authorization or Cookie headers"