Add OAuth2/OpenID Connect authorization server
Implement a full OAuth2 2.0 and OpenID Connect 1.0 authorization server with support for authorization code flow (with PKCE), refresh token rotation, device authorization grant, dynamic client registration, token introspection, and token revocation. Includes database schema, coredata layer, service logic, HTTP handlers, OIDC discovery endpoint, and JWKS publishing. Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
@@ -19,7 +19,19 @@ import (
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func SHA256Hex(data []byte) string {
|
||||
func SHA256(data []byte) []byte {
|
||||
h := sha256.Sum256(data)
|
||||
return hex.EncodeToString(h[:])
|
||||
return h[:]
|
||||
}
|
||||
|
||||
func SHA256String(s string) []byte {
|
||||
return SHA256([]byte(s))
|
||||
}
|
||||
|
||||
func SHA256Hex(data []byte) string {
|
||||
return hex.EncodeToString(SHA256(data))
|
||||
}
|
||||
|
||||
func SHA256HexString(s string) string {
|
||||
return SHA256Hex([]byte(s))
|
||||
}
|
||||
|
||||
98
pkg/crypto/jose/jose.go
Normal file
98
pkg/crypto/jose/jose.go
Normal file
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package jose
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
type (
|
||||
// JWK represents a JSON Web Key (RFC 7517).
|
||||
JWK struct {
|
||||
KeyType string `json:"kty"`
|
||||
Use string `json:"use"`
|
||||
Algorithm string `json:"alg"`
|
||||
KeyID string `json:"kid"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
}
|
||||
|
||||
// JWKS represents a JSON Web Key Set (RFC 7517).
|
||||
JWKS struct {
|
||||
Keys []JWK `json:"keys"`
|
||||
}
|
||||
|
||||
// JWTHeader represents a JWT header (RFC 7519).
|
||||
JWTHeader struct {
|
||||
Algorithm string `json:"alg"`
|
||||
Type string `json:"typ"`
|
||||
KeyID string `json:"kid"`
|
||||
}
|
||||
)
|
||||
|
||||
// RSAPublicKeyToJWK converts an RSA public key to a JWK with the given
|
||||
// key ID, marked for RS256 signature use.
|
||||
func RSAPublicKeyToJWK(pub *rsa.PublicKey, kid string) JWK {
|
||||
return JWK{
|
||||
KeyType: "RSA",
|
||||
Use: "sig",
|
||||
Algorithm: "RS256",
|
||||
KeyID: kid,
|
||||
N: base64.RawURLEncoding.EncodeToString(pub.N.Bytes()),
|
||||
E: base64.RawURLEncoding.EncodeToString(big.NewInt(int64(pub.E)).Bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
// SignJWT signs arbitrary claims as a JWT using RS256 with the given RSA
|
||||
// private key and key ID. The claims value is JSON-marshaled as the payload.
|
||||
func SignJWT(privateKey *rsa.PrivateKey, kid string, claims any) (string, error) {
|
||||
header := JWTHeader{
|
||||
Algorithm: "RS256",
|
||||
Type: "JWT",
|
||||
KeyID: kid,
|
||||
}
|
||||
|
||||
headerJSON, err := json.Marshal(header)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot marshal jwt header: %w", err)
|
||||
}
|
||||
|
||||
claimsJSON, err := json.Marshal(claims)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot marshal jwt claims: %w", err)
|
||||
}
|
||||
|
||||
headerB64 := base64.RawURLEncoding.EncodeToString(headerJSON)
|
||||
claimsB64 := base64.RawURLEncoding.EncodeToString(claimsJSON)
|
||||
|
||||
signingInput := headerB64 + "." + claimsB64
|
||||
|
||||
h := sha256.Sum256([]byte(signingInput))
|
||||
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, h[:])
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot sign jwt: %w", err)
|
||||
}
|
||||
|
||||
signatureB64 := base64.RawURLEncoding.EncodeToString(signature)
|
||||
|
||||
return signingInput + "." + signatureB64, nil
|
||||
}
|
||||
288
pkg/crypto/jose/jose_test.go
Normal file
288
pkg/crypto/jose/jose_test.go
Normal file
@@ -0,0 +1,288 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package jose_test
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"math/big"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.probo.inc/probo/pkg/crypto/jose"
|
||||
)
|
||||
|
||||
func testRSAKey(t *testing.T) *rsa.PrivateKey {
|
||||
t.Helper()
|
||||
|
||||
key, err := rsa.GenerateKey(
|
||||
strings.NewReader(strings.Repeat("deterministic-seed-for-test!!!!!", 100)),
|
||||
2048,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
func TestRSAPublicKeyToJWK(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key := testRSAKey(t)
|
||||
|
||||
t.Run(
|
||||
"sets fixed RSA signature fields",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwk := jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-1")
|
||||
|
||||
assert.Equal(t, "RSA", jwk.KeyType)
|
||||
assert.Equal(t, "sig", jwk.Use)
|
||||
assert.Equal(t, "RS256", jwk.Algorithm)
|
||||
assert.Equal(t, "kid-1", jwk.KeyID)
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"encodes modulus correctly",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwk := jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-1")
|
||||
|
||||
nBytes, err := base64.RawURLEncoding.DecodeString(jwk.N)
|
||||
require.NoError(t, err)
|
||||
|
||||
n := new(big.Int).SetBytes(nBytes)
|
||||
assert.Equal(t, key.N, n)
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"encodes exponent correctly",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwk := jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-1")
|
||||
|
||||
eBytes, err := base64.RawURLEncoding.DecodeString(jwk.E)
|
||||
require.NoError(t, err)
|
||||
|
||||
e := new(big.Int).SetBytes(eBytes)
|
||||
assert.Equal(t, int64(key.E), e.Int64())
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"different key IDs produce different JWKs",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwk1 := jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-a")
|
||||
jwk2 := jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-b")
|
||||
|
||||
assert.Equal(t, "kid-a", jwk1.KeyID)
|
||||
assert.Equal(t, "kid-b", jwk2.KeyID)
|
||||
assert.Equal(t, jwk1.N, jwk2.N)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestSignJWT(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key := testRSAKey(t)
|
||||
|
||||
t.Run(
|
||||
"produces valid three-part JWT",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
claims := map[string]string{"sub": "test"}
|
||||
|
||||
token, err := jose.SignJWT(key, "kid-1", claims)
|
||||
require.NoError(t, err)
|
||||
|
||||
parts := strings.Split(token, ".")
|
||||
assert.Len(t, parts, 3)
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"header contains correct fields",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
claims := map[string]string{"sub": "test"}
|
||||
|
||||
token, err := jose.SignJWT(key, "my-kid", claims)
|
||||
require.NoError(t, err)
|
||||
|
||||
parts := strings.Split(token, ".")
|
||||
headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
require.NoError(t, err)
|
||||
|
||||
var header jose.JWTHeader
|
||||
err = json.Unmarshal(headerJSON, &header)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "RS256", header.Algorithm)
|
||||
assert.Equal(t, "JWT", header.Type)
|
||||
assert.Equal(t, "my-kid", header.KeyID)
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"claims are correctly encoded",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
claims := map[string]any{
|
||||
"iss": "https://issuer.example.com",
|
||||
"sub": "sub-123",
|
||||
"aud": "aud-456",
|
||||
}
|
||||
|
||||
token, err := jose.SignJWT(key, "kid-1", claims)
|
||||
require.NoError(t, err)
|
||||
|
||||
parts := strings.Split(token, ".")
|
||||
claimsJSON, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
require.NoError(t, err)
|
||||
|
||||
var decoded map[string]any
|
||||
err = json.Unmarshal(claimsJSON, &decoded)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "https://issuer.example.com", decoded["iss"])
|
||||
assert.Equal(t, "sub-123", decoded["sub"])
|
||||
assert.Equal(t, "aud-456", decoded["aud"])
|
||||
},
|
||||
)
|
||||
|
||||
t.Run(
|
||||
"signature is verifiable",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
claims := map[string]string{"sub": "test"}
|
||||
|
||||
token, err := jose.SignJWT(key, "kid-1", claims)
|
||||
require.NoError(t, err)
|
||||
|
||||
parts := strings.Split(token, ".")
|
||||
signingInput := parts[0] + "." + parts[1]
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||
require.NoError(t, err)
|
||||
|
||||
h := sha256.Sum256([]byte(signingInput))
|
||||
err = rsa.VerifyPKCS1v15(&key.PublicKey, crypto.SHA256, h[:], signature)
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestJWK_JSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key := testRSAKey(t)
|
||||
|
||||
t.Run(
|
||||
"marshals to expected JSON field names",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwk := jose.RSAPublicKeyToJWK(&key.PublicKey, "test-kid")
|
||||
|
||||
data, err := json.Marshal(jwk)
|
||||
require.NoError(t, err)
|
||||
|
||||
var raw map[string]string
|
||||
err = json.Unmarshal(data, &raw)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "RSA", raw["kty"])
|
||||
assert.Equal(t, "sig", raw["use"])
|
||||
assert.Equal(t, "RS256", raw["alg"])
|
||||
assert.Equal(t, "test-kid", raw["kid"])
|
||||
assert.NotEmpty(t, raw["n"])
|
||||
assert.NotEmpty(t, raw["e"])
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestJWKS_JSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key := testRSAKey(t)
|
||||
|
||||
t.Run(
|
||||
"marshals keys array",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
jwks := jose.JWKS{
|
||||
Keys: []jose.JWK{
|
||||
jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-1"),
|
||||
jose.RSAPublicKeyToJWK(&key.PublicKey, "kid-2"),
|
||||
},
|
||||
}
|
||||
|
||||
data, err := json.Marshal(jwks)
|
||||
require.NoError(t, err)
|
||||
|
||||
var raw struct {
|
||||
Keys []json.RawMessage `json:"keys"`
|
||||
}
|
||||
err = json.Unmarshal(data, &raw)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Len(t, raw.Keys, 2)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func TestJWTHeader_JSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run(
|
||||
"marshals to expected JSON field names",
|
||||
func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
header := jose.JWTHeader{
|
||||
Algorithm: "RS256",
|
||||
Type: "JWT",
|
||||
KeyID: "my-kid",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(header)
|
||||
require.NoError(t, err)
|
||||
|
||||
var raw map[string]string
|
||||
err = json.Unmarshal(data, &raw)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "RS256", raw["alg"])
|
||||
assert.Equal(t, "JWT", raw["typ"])
|
||||
assert.Equal(t, "my-kid", raw["kid"])
|
||||
},
|
||||
)
|
||||
}
|
||||
73
pkg/crypto/rand/rand.go
Normal file
73
pkg/crypto/rand/rand.go
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
// PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
package rand
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// HexString returns a hex-encoded cryptographically random string.
|
||||
// The output is 2*byteLen characters long.
|
||||
func HexString(byteLen int) (string, error) {
|
||||
b := make([]byte, byteLen)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("cannot generate random bytes: %w", err)
|
||||
}
|
||||
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// MustHexString is like HexString but panics if the system entropy source is
|
||||
// unavailable.
|
||||
func MustHexString(byteLen int) string {
|
||||
s, err := HexString(byteLen)
|
||||
if err != nil {
|
||||
panic("rand: crypto/rand is unavailable: " + err.Error())
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// StringFromAlphabet returns a random string of length n, where each character
|
||||
// is drawn uniformly from alphabet using crypto/rand.
|
||||
func StringFromAlphabet(alphabet string, n int) (string, error) {
|
||||
max := big.NewInt(int64(len(alphabet)))
|
||||
buf := make([]byte, n)
|
||||
|
||||
for i := range buf {
|
||||
idx, err := rand.Int(rand.Reader, max)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot generate random bytes: %w", err)
|
||||
}
|
||||
|
||||
buf[i] = alphabet[idx.Int64()]
|
||||
}
|
||||
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// MustStringFromAlphabet is like StringFromAlphabet but panics if the system
|
||||
// entropy source is unavailable.
|
||||
func MustStringFromAlphabet(alphabet string, n int) string {
|
||||
s, err := StringFromAlphabet(alphabet, n)
|
||||
if err != nil {
|
||||
panic("rand: crypto/rand is unavailable: " + err.Error())
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
Reference in New Issue
Block a user