auth/jwt/module.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
ac05eb49125124a4414385be981ec2cb936e4a4c
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

//! Strict synchronous HS256 JWT Standard Library module.
//! Caller-provided trusted keys, policy and Instant; no ambient authority.
//! Only issue, verify and JwtError are public.

/// Prototype for a fresh JWT authentication or token-format failure.
this.JwtError: Error {}

/// Issue a canonical compact HS256 JWT from explicit structured JSON claims.
this.issue: (claims, signingKey, policy, now) => {
    JSON: import("std:json/json")
    Base64url: import("std:text/base64url")
    HMAC: import("std:crypto/hmac_sha256")
    Compact: import("./internal/Compact.protos")
    Policy: import("./internal/Policy.protos")
    Claims: import("./internal/Claims.protos")

    capturedPolicy: Policy.capture(policy)
    key: Policy.key(signingKey)
    nowNanoseconds: Policy.time(now)

    // Bound traversal of issuer-controlled structured JSON first.
    // JSON.encode is not the admission boundary for excessive depth.
    Claims.requireObject(claims)
    Claims.validateDepth(claims, 16)
    Policy.validateClaims(claims, capturedPolicy, nowNanoseconds)

    // All issuer-controlled arguments must be valid before signing.
    encoded: JSON.encode(claims)
    payloadBytes: Compact.boundedUtf8(encoded, 4096)

    parsed: JSON.parse(Encoding.UTF8.decode(payloadBytes))
    Policy.validateClaims(parsed, capturedPolicy, nowNanoseconds)

    header: JSON.object(
        "alg", JSON.string("HS256"),
        "typ", JSON.string(capturedPolicy.type)
    )

    headerText: JSON.encode(header)
    headerBytes: Compact.boundedUtf8(headerText, 1024)

    headerSegment: Base64url.encode(headerBytes)
    payloadSegment: Base64url.encode(payloadBytes)

    signingInput: headerSegment + "." + payloadSegment
    signingInputBytes: Encoding.Latin1.encode(signingInput)

    signature: HMAC.digest(key, signingInputBytes)
    signatureSegment: Base64url.encode(signature)

    Compact.assemble(
        headerSegment,
        payloadSegment,
        signatureSegment
    )
}

/// Verify a compact HS256 JWT and return claims only after authentication.
this.verify: (token, verificationKey, policy, now) => {
    JSON: import("std:json/json")
    Base64url: import("std:text/base64url")
    HMAC: import("std:crypto/hmac_sha256")
    Compact: import("./internal/Compact.protos")
    Policy: import("./internal/Policy.protos")

    capturedPolicy: Policy.capture(policy)
    key: Policy.key(verificationKey)
    nowNanoseconds: Policy.time(now)

    // Untrusted compact and JSON formatting failures become JwtError.
    parts: null
    headerNode: null
    signature: null

    Error.handle(
        () => {
            parts = Compact.split(token)

            decodedHeader: Base64url.decode(parts.header)
            Compact.headerBytes(decodedHeader)

            headerText: Compact.jsonText(decodedHeader)
            headerNode = JSON.parse(headerText)

            signature = Base64url.decode(parts.signature)
        },
        (error) => {
            JwtError().signal()
        }
    )

    Error.handle(
        () => {
            (headerNode.kind === "object").ifFalse(() => {
                Error().signal()
            })

            members: headerNode.value

            (members.size() == 2).ifFalse(() => {
                Error().signal()
            })

            members.containsKey("alg").ifFalse(() => {
                Error().signal()
            })

            members.containsKey("typ").ifFalse(() => {
                Error().signal()
            })

            alg: members["alg"]
            typ: members["typ"]

            (alg.kind === "string").ifFalse(() => {
                Error().signal()
            })

            (typ.kind === "string").ifFalse(() => {
                Error().signal()
            })

            (alg.value == "HS256").ifFalse(() => {
                Error().signal()
            })

            (typ.value == capturedPolicy.type).ifFalse(() => {
                Error().signal()
            })

            (signature.size() == 32).ifFalse(() => {
                Error().signal()
            })
        },
        (error) => {
            JwtError().signal()
        }
    )

    // Preserve the original encoded segments for authentication.
    signingInputBytes: Encoding.Latin1.encode(parts.signingInput)

    // Do not catch provider failures as malformed-token failures.
    authenticated: HMAC.verify(
        key,
        signingInputBytes,
        signature
    )

    authenticated.ifFalse(() => {
        JwtError().signal()
    })

    // The payload is never parsed or returned before MAC verification.
    verifiedClaims: null

    Error.handle(
        () => {
            payloadBytes: Base64url.decode(parts.payload)
            Compact.payloadBytes(payloadBytes)

            payloadText: Compact.jsonText(payloadBytes)
            verifiedClaims = JSON.parse(payloadText)

            Policy.validateClaims(
                verifiedClaims,
                capturedPolicy,
                nowNanoseconds
            )
        },
        (error) => {
            JwtError().signal()
        }
    )

    verifiedClaims
}