Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for Latvian eID Eparaksts #3826

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .schemastore/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@
},
"provider": {
"title": "Provider",
"description": "Can be one of github, github-app, gitlab, generic, google, microsoft, discord, salesforce, slack, facebook, auth0, vk, yandex, apple, spotify, netid, dingtalk, patreon.",
"description": "Can be one of github, github-app, gitlab, generic, google, microsoft, discord, salesforce, slack, facebook, auth0, vk, yandex, apple, spotify, netid, dingtalk, patreon, eparaksts, eparaksts-mobile.",
"type": "string",
"enum": [
"github",
Expand All @@ -456,7 +456,9 @@
"linkedin",
"linkedin_v2",
"lark",
"x"
"x",
"eparaksts",
"eparaksts-mobile"
],
"examples": ["google"]
},
Expand Down
6 changes: 4 additions & 2 deletions embedx/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@
},
"provider": {
"title": "Provider",
"description": "Can be one of github, github-app, gitlab, generic, google, microsoft, discord, salesforce, slack, facebook, auth0, vk, yandex, apple, spotify, netid, dingtalk, patreon.",
"description": "Can be one of github, github-app, gitlab, generic, google, microsoft, discord, salesforce, slack, facebook, auth0, vk, yandex, apple, spotify, netid, dingtalk, patreon, eparaksts, eparaksts-mobile.",
"type": "string",
"enum": [
"github",
Expand All @@ -456,7 +456,9 @@
"linkedin",
"linkedin_v2",
"lark",
"x"
"x",
"eparaksts",
"eparaksts-mobile"
],
"examples": ["google"]
},
Expand Down
48 changes: 26 additions & 22 deletions selfservice/strategy/oidc/provider_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ type Configuration struct {
// - dingtalk
// - linkedin
// - patreon
// - eparaksts
// - eparaksts-mobile
Provider string `json:"provider"`

// Label represents an optional label which can be used in the UI generation.
Expand Down Expand Up @@ -142,28 +144,30 @@ type ConfigurationCollection struct {
// If you add a provider here, please also add a test to
// provider_private_net_test.go
var supportedProviders = map[string]func(config *Configuration, reg Dependencies) Provider{
"generic": NewProviderGenericOIDC,
"google": NewProviderGoogle,
"github": NewProviderGitHub,
"github-app": NewProviderGitHubApp,
"gitlab": NewProviderGitLab,
"microsoft": NewProviderMicrosoft,
"discord": NewProviderDiscord,
"salesforce": NewProviderSalesforce,
"slack": NewProviderSlack,
"facebook": NewProviderFacebook,
"auth0": NewProviderAuth0,
"vk": NewProviderVK,
"yandex": NewProviderYandex,
"apple": NewProviderApple,
"spotify": NewProviderSpotify,
"netid": NewProviderNetID,
"dingtalk": NewProviderDingTalk,
"linkedin": NewProviderLinkedIn,
"linkedin_v2": NewProviderLinkedInV2,
"patreon": NewProviderPatreon,
"lark": NewProviderLark,
"x": NewProviderX,
"generic": NewProviderGenericOIDC,
"google": NewProviderGoogle,
"github": NewProviderGitHub,
"github-app": NewProviderGitHubApp,
"gitlab": NewProviderGitLab,
"microsoft": NewProviderMicrosoft,
"discord": NewProviderDiscord,
"salesforce": NewProviderSalesforce,
"slack": NewProviderSlack,
"facebook": NewProviderFacebook,
"auth0": NewProviderAuth0,
"vk": NewProviderVK,
"yandex": NewProviderYandex,
"apple": NewProviderApple,
"spotify": NewProviderSpotify,
"netid": NewProviderNetID,
"dingtalk": NewProviderDingTalk,
"linkedin": NewProviderLinkedIn,
"linkedin_v2": NewProviderLinkedInV2,
"patreon": NewProviderPatreon,
"lark": NewProviderLark,
"x": NewProviderX,
"eparaksts": NewProviderEParaksts,
"eparaksts-mobile": NewProviderEParakstsMobile,
}

func (c ConfigurationCollection) Provider(id string, reg Dependencies) (Provider, error) {
Expand Down
152 changes: 152 additions & 0 deletions selfservice/strategy/oidc/provider_eparaksts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0

package oidc

import (
"context"
"encoding/json"
"net/url"
"path"
"strings"

"github.com/hashicorp/go-retryablehttp"

"github.com/ory/x/httpx"

"github.com/pkg/errors"
"golang.org/x/oauth2"

"github.com/ory/herodot"
)

type ProviderEParaksts struct {
config *Configuration
reg Dependencies
acrValue string
}

func NewProviderEParaksts(
config *Configuration,
reg Dependencies,
) Provider {
return &ProviderEParaksts{
config: config,
reg: reg,
acrValue: "urn:eparaksts:authentication:flow:sc_plugin",
}
}

func NewProviderEParakstsMobile(
config *Configuration,
reg Dependencies,
) Provider {
return &ProviderEParaksts{
config: config,
reg: reg,
acrValue: "urn:eparaksts:authentication:flow:mobileid",
}
}

func (g *ProviderEParaksts) Config() *Configuration {
return g.config
}

func (g *ProviderEParaksts) oauth2(ctx context.Context) (*oauth2.Config, error) {
endpoint, err := url.Parse(g.config.IssuerURL)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}

authUrl := *endpoint
authUrl.Path = path.Join(authUrl.Path, "/trustedx-authserver/oauth/lvrtc-eipsign-as")

values := url.Values{}
values.Add("prompt", "login")
values.Add("acr_values", g.acrValue)
values.Add("ui_locales", "lv")
authUrl.RawQuery = values.Encode()

tokenUrl := *endpoint
tokenUrl.Path = path.Join(tokenUrl.Path, "/trustedx-authserver/oauth/lvrtc-eipsign-as/token")

c := &oauth2.Config{
ClientID: g.config.ClientID,
ClientSecret: g.config.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: authUrl.String(),
TokenURL: tokenUrl.String(),
},
Scopes: g.config.Scope,
RedirectURL: g.config.Redir(g.reg.Config().OIDCRedirectURIBase(ctx)),
}
return c, nil
}

func (g *ProviderEParaksts) AuthCodeURLOptions(r ider) []oauth2.AuthCodeOption {
return []oauth2.AuthCodeOption{}
}

func (g *ProviderEParaksts) OAuth2(ctx context.Context) (*oauth2.Config, error) {
return g.oauth2(ctx)
}

func (g *ProviderEParaksts) Claims(ctx context.Context, exchange *oauth2.Token, query url.Values) (*Claims, error) {
o, err := g.OAuth2(ctx)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}

u, err := url.Parse(g.config.IssuerURL)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}
u.Path = path.Join(u.Path, "/trustedx-resources/openid/v1/users/me")

ctx, client := httpx.SetOAuth2(ctx, g.reg.HTTPClient(ctx), o, exchange)
req, err := retryablehttp.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}

req.Header.Add("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}
defer resp.Body.Close()

if err := logUpstreamError(g.reg.Logger(), resp); err != nil {
return nil, err
}

type User struct {
Subject string `json:"sub,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
SerialNumber string `json:"serial_number,omitempty"`
}
var user User

if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("%s", err))
}

serialNumberDigits := g.ParseSerialNumber(user.SerialNumber)

return &Claims{
Issuer: g.config.IssuerURL,
Subject: user.Subject,
RawClaims: map[string]interface{}{
"serial_number": serialNumberDigits,
},
GivenName: user.GivenName,
LastName: user.FamilyName,
}, nil
}

func (g *ProviderEParaksts) ParseSerialNumber(serialNumber string) string {
serialNumber = serialNumber[6:]
return strings.Replace(serialNumber, "-", "", -1)
}
105 changes: 105 additions & 0 deletions selfservice/strategy/oidc/provider_eparaksts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

package oidc_test

import (
"context"
"net/http"
"net/url"
"testing"
"time"

"github.com/hashicorp/go-retryablehttp"
"github.com/jarcoal/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"

"github.com/ory/kratos/internal"
"github.com/ory/kratos/selfservice/strategy/oidc"
)

type User struct {
SerialNumber string
ParseSerialNumber (oidc.ProviderEParaksts)
}

func TestProviderEparaksts_ParseSerialNumber(t *testing.T) {
expected := "1234678900"
serialNumber := "PVOLV-12346-78900"

g := &oidc.ProviderEParaksts{}

actual := g.ParseSerialNumber(serialNumber)
assert.Equal(t, expected, actual)
}

func TestProviderEparaksts_Discovery(t *testing.T) {
_, reg := internal.NewVeryFastRegistryWithoutDB(t)

p := oidc.NewProviderEParakstsMobile(&oidc.Configuration{
ID: "eparaksts",
Provider: "eparaksts",
ClientID: "abcd",
ClientSecret: "secret",
IssuerURL: "https://eidas.eparaksts.lv",
Mapper: "file://./stub/oidc.eparaksts.jsonnet",
Scope: []string{"urn:lvrtc:fpeil:aa"},
}, reg)

c, err := p.(oidc.OAuth2Provider).OAuth2(context.Background())
require.NoError(t, err)
assert.Contains(t, c.Scopes, "urn:lvrtc:fpeil:aa")
assert.Equal(t, "https://eidas.eparaksts.lv/trustedx-authserver/oauth/lvrtc-eipsign-as/token", c.Endpoint.TokenURL)
assert.Equal(t, "https://eidas.eparaksts.lv/trustedx-authserver/oauth/lvrtc-eipsign-as?acr_values=urn%3Aeparaksts%3Aauthentication%3Aflow%3Amobileid&prompt=login&ui_locales=lv", c.Endpoint.AuthURL)
}

func TestProviderEparaksts_Claims(t *testing.T) {
_, base := internal.NewFastRegistryWithMocks(t)
reg := &mockRegistry{base, retryablehttp.NewClient()}
httpmock.ActivateNonDefault(reg.cl.HTTPClient)
t.Cleanup(httpmock.DeactivateAndReset)

httpmock.RegisterResponder("GET", "https://eidas-demo.eparaksts.lv/trustedx-resources/openid/v1/users/me",
func(req *http.Request) (*http.Response, error) {
resp, err := httpmock.NewJsonResponse(200, map[string]interface{}{
"sub": "5foOWOiYXD",
"acr": "urn:eparaksts:authentication:flow:sc_plugin",
"domain": "citizen",
"given_name": "John",
"family_name": "Doe",
"name": "John Doe",
"serial_number": "PVOLV-12346-78900",
})
return resp, err
})

c := &oidc.Configuration{
ID: "eparaksts",
Provider: "eparaksts",
ClientID: "abcd",
ClientSecret: "secret",
IssuerURL: "https://eidas-demo.eparaksts.lv",
Mapper: "file://./stub/oidc.eparaksts.jsonnet",
Scope: []string{"urn:lvrtc:fpeil:aa"},
}
eparaksts := oidc.NewProviderEParaksts(c, reg)

actual, err := eparaksts.(oidc.OAuth2Provider).Claims(
context.Background(),
(&oauth2.Token{AccessToken: "foo", Expiry: time.Now().Add(time.Hour)}),
url.Values{},
)
require.NoError(t, err)

assert.Equal(t, &oidc.Claims{
Issuer: "https://eidas-demo.eparaksts.lv",
Subject: "5foOWOiYXD",
GivenName: "John",
LastName: "Doe",
RawClaims: map[string]interface{}{
"serial_number": "1234678900",
},
}, actual)
}
Loading