Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
charset = utf-8
indent_style = tab
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
+9
View File
@@ -0,0 +1,9 @@
/vendor
/bin
/.gopath
/golint.txt
/govet.txt
/test/tests.*
/tests.output
/tests.xml
/coverage.out
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
Kopano oidc-go
Copyright 2017 - 2022 Kopano and its licensors
This product includes software developed at
Kopano (https://kopano.com/).
+10
View File
@@ -0,0 +1,10 @@
# oidc-go [![GoDoc](https://godoc.org/github.com/libregraph/oidc-go?status.svg)](https://godoc.org/github.com/libregraph/oidc-go)
Oidc-go is a Go package to provide common helpers to interface with OpenID
Connect servers.
## Installation
```text
go get github.com/libregraph/oidc-go
```
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright 2018-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
const (
// ApplicationTypeWeb is the string value for the OpenID Connect client
// application_type web.
ApplicationTypeWeb = "web"
// ApplicationTypeNative is the string value for the OpenID Connect client
// application_type web.
ApplicationTypeNative = "native"
)
+26
View File
@@ -0,0 +1,26 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// Auth method string values as defined by OpenID Connect Core 1.0.
const (
AuthMethodClientSecretPost = "client_secret_post"
AuthMethodClientSecretBasic = "client_secret_basic"
AuthMethodClientSecretJWT = "client_secret_jwt"
AuthMethodPrivateKeyJWT = "private_key_jwt"
AuthMethodNone = "none"
)
+54
View File
@@ -0,0 +1,54 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// Standard claims as used in JSON Web Tokens.
const (
IssuerIdentifierClaim = "iss"
SubjectIdentifierClaim = "sub"
AudienceClaim = "aud"
ExpirationClaim = "exp"
IssuedAtClaim = "iat"
)
// Additional claims as defined by OIDC.
const (
NameClaim = "name"
FamilyNameClaim = "family_name"
GivenNameClaim = "given_name"
MiddleNameClaim = "middle_name"
NicknameClaim = "nickname"
PreferredUsernameClaim = "preferred_username"
ProfileClaim = "profile"
PictureClaim = "picture"
WebsiteClaim = "website"
GenderClaim = "gender"
BirthdateClaim = "birthdate"
ZoneinfoClaim = "zoneinfo"
LocaleClaim = "locale"
UpdatedAtClaim = "updated_at"
EmailClaim = "email"
EmailVerifiedClaim = "email_verified"
AuthTimeClaim = "auth_time"
)
// Additional claims as defined by OIDC extensions.
const (
SessionIDClaim = "sid"
)
+74
View File
@@ -0,0 +1,74 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
)
// Code challenge methods implemented by Konnect. See https://tools.ietf.org/html/rfc7636.
const (
PlainCodeChallengeMethod = "plain"
S256CodeChallengeMethod = "S256"
)
// ValidateCodeChallenge implements https://tools.ietf.org/html/rfc7636#section-4.6
// code challenge verification.
func ValidateCodeChallenge(challenge string, method string, verifier string) error {
if method == "" {
// We default to S256CodeChallengeMethod.
method = S256CodeChallengeMethod
}
computed, err := MakeCodeChallenge(method, verifier)
if err != nil {
return err
}
if subtle.ConstantTimeCompare([]byte(challenge), []byte(computed)) != 1 {
return errors.New("invalid code challenge")
}
return nil
}
// MakeCodeChallenge creates a code challenge using the provided method and
// verifier for https://tools.ietf.org/html/rfc7636#section-4.6 verification.
func MakeCodeChallenge(method string, verifier string) (string, error) {
if verifier == "" {
return "", errors.New("invalid verifier")
}
switch method {
case PlainCodeChallengeMethod:
// Challenge is verifier.
return verifier, nil
case S256CodeChallengeMethod:
// BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
// Base64 encoding using the URL- and filename-safe character set
// defined in Section 5 of [RFC4648], with all trailing '='
// characters omitted (as permitted by Section 3.2 of [RFC4648]) and
// without the inclusion of any line breaks, whitespace, or other
// additional characters.
sum := sha256.Sum256([]byte(verifier))
return base64.RawURLEncoding.EncodeToString(sum[:]), nil
}
return "", errors.New("transform algorithm not supported")
}
+45
View File
@@ -0,0 +1,45 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// OAuth2 error codes.
const (
ErrorCodeOAuth2UnsupportedResponseType = "unsupported_response_type"
ErrorCodeOAuth2InvalidRequest = "invalid_request"
ErrorCodeOAuth2InvalidToken = "invalid_token"
ErrorCodeOAuth2InsufficientScope = "insufficient_scope"
ErrorCodeOAuth2InvalidGrant = "invalid_grant"
ErrorCodeOAuth2UnsupportedGrantType = "unsupported_grant_type"
ErrorCodeOAuth2AccessDenied = "access_denied"
ErrorCodeOAuth2ServerError = "server_error"
ErrorCodeOAuth2TemporarilyUnavailable = "temporarily_unavailable"
)
// OIDC error codes.
const (
ErrorCodeOIDCInteractionRequired = "interaction_required"
ErrorCodeOIDCLoginRequired = "login_required"
ErrorCodeOIDCConsentRequired = "consent_required"
ErrorCodeOIDCRequestNotSupported = "request_not_supported"
ErrorCodeOIDCInvalidRequestObject = "invalid_request_object"
ErrorCodeOIDCRequestURINotSupported = "request_uri_not_supported"
ErrorCodeOIDCRegistrationNotSupported = "registration_not_supported"
ErrorCodeOIDCInvalidRedirectURI = "invalid_redirect_uri"
ErrorCodeOIDCInvalidClientMetadata = "invalid_client_metadata"
)
+35
View File
@@ -0,0 +1,35 @@
/*
* Copyright 2017 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// OIDC response types and flows.
const (
ResponseTypeCode = "code" // OIDC code flow
ResponseTypeIDTokenToken = "id_token token" // OIDC implicit flow
ResponseTypeIDToken = "id_token" // OIDC implicit flow
ResponseTypeCodeIDToken = "code id_token" // OIDC hybrid flow
ResponseTypeCodeToken = "code token" // OIDC hybrid flow
ResponseTypeCodeIDTokenToken = "code id_token token" // OIDC hybrid flow
ResponseTypeToken = "token" // OAuth2
ResponseModeFragment = "fragment"
ResponseModeQuery = "query"
FlowCode = "code"
FlowImplicit = "implicit"
FlowHybrid = "hybrid"
)
+31
View File
@@ -0,0 +1,31 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
const (
// GrantTypeAuthorizationCode is the string value for the
// OAuth2 authroization code token request grant type.
GrantTypeAuthorizationCode = "authorization_code"
// GrantTypeImplicit is the string value for the OAuth2 id_token, token
// id_token token request grant type.
GrantTypeImplicit = "implicit"
// GrantTypeRefreshToken is the string value for the OAuth2 refresh_token
// token request grant_type.
GrantTypeRefreshToken = "refresh_token"
)
+86
View File
@@ -0,0 +1,86 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
import (
"crypto"
"encoding/base64"
"fmt"
)
// LeftmostHashBytes defines []bytes with Base64URL encoder via String().
type LeftmostHashBytes []byte
// LeftmostHash hashes the provided data with the provided hash function and
// returns the left-most half the hashed bytes.
func LeftmostHash(data []byte, hash crypto.Hash) LeftmostHashBytes {
hasher := hash.New()
hasher.Write(data)
result := hasher.Sum(nil)
return LeftmostHashBytes(result[:len(result)/2])
}
// String returns the Base64URL encoded string of the accociated bytes.
func (lmhb LeftmostHashBytes) String() string {
return base64.RawURLEncoding.EncodeToString(lmhb)
}
// HashFromSigningMethod returns the matching crypto.Hash for the provided
// signing alg.
func HashFromSigningMethod(alg string) (hash crypto.Hash, err error) {
switch alg {
case "HS256":
fallthrough
case "RS256":
fallthrough
case "PS256":
fallthrough
case "ES256":
hash = crypto.SHA256
case "HS386":
fallthrough
case "RS384":
fallthrough
case "PS384":
fallthrough
case "ES384":
hash = crypto.SHA384
case "HS512":
fallthrough
case "RS512":
fallthrough
case "PS512":
fallthrough
case "ES512":
hash = crypto.SHA512
case "EdDSA":
hash = crypto.SHA512
default:
err = fmt.Errorf("Unkown alg %s", alg)
}
if !hash.Available() {
err = fmt.Errorf("Hash for %s is not available", alg)
}
return
}
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/pquerna/cachecontrol"
)
// Basic HTTP related global settings.
var (
DefaultHTTPClient *http.Client
DefaultHTTPHeader http.Header
DefaultMaxJSONFetchSize int64 = 5 * 1024 * 1024 // 5 MiB
DefaultJSONFetchExpiry = time.Minute * 1
DefaultJSONFetchRetry = time.Second * 3
)
func fetchJSON(ctx context.Context, u *url.URL, dst interface{}, client *http.Client, header http.Header) (time.Duration, error) {
if client == nil {
client = DefaultHTTPClient
if client == nil {
client = http.DefaultClient
}
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return DefaultJSONFetchRetry, fmt.Errorf("failed create fetch JSON request: %v", err)
}
if header == nil {
header = DefaultHTTPHeader
}
if header != nil {
for h, values := range header {
for _, v := range values {
req.Header.Add(h, v)
}
}
}
res, err := client.Do(req.WithContext(ctx))
if err != nil {
return DefaultJSONFetchRetry, fmt.Errorf("failed to fetch JSON: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return DefaultJSONFetchRetry, fmt.Errorf("failed to fetch JSON (status: %d)", res.StatusCode)
}
_, expires, _ := cachecontrol.CachableResponse(req, res, cachecontrol.Options{})
err = json.NewDecoder(io.LimitReader(res.Body, DefaultMaxJSONFetchSize)).Decode(dst)
if err != nil {
return DefaultJSONFetchRetry, fmt.Errorf("failed to fetch JSON: %v", err)
}
expirationDuration := expires.Sub(time.Now())
if expirationDuration < DefaultJSONFetchRetry {
if err == nil {
expirationDuration = DefaultJSONFetchExpiry
} else {
expirationDuration = DefaultJSONFetchRetry
}
}
return expirationDuration, err
}
+31
View File
@@ -0,0 +1,31 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
type logger interface {
Printf(string, ...interface{})
}
type noopLogger struct {
}
func (log *noopLogger) Printf(string, ...interface{}) {
}
// DefaultLogger is the logger used by this library if no other is explicitly
// specified.
var DefaultLogger logger = &noopLogger{}
+17
View File
@@ -0,0 +1,17 @@
/*
* Copyright 2019 - 2022 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc // import "github.com/libregraph/oidc-go"
+26
View File
@@ -0,0 +1,26 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// OIDC prompt values.
// See http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
const (
PromptNone = "none"
PromptLogin = "login"
PromptConsent = "consent"
PromptSelectAccount = "select_account"
)
+310
View File
@@ -0,0 +1,310 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"github.com/desertbit/timer"
"github.com/go-jose/go-jose/v3"
)
// Provider represents an OpenID Connect server's configuration.
type Provider struct {
mutex sync.RWMutex
initialized bool
ready chan struct{}
started chan error
cancel context.CancelFunc
issuer string
wellKnownURI *url.URL
jwksURI *url.URL
logger logger
httpClient *http.Client
httpHeader http.Header
wellKnown *WellKnown
jwks *jose.JSONWebKeySet
}
// ProviderConfig bundles configuration for a Provider.
type ProviderConfig struct {
HTTPClient *http.Client
HTTPHeader http.Header
WellKnownURI *url.URL
Logger logger
}
// DefaultProviderConfig is the Provider configuration uses when none was
// explicitly specified.
var DefaultProviderConfig = &ProviderConfig{}
// ProviderDefinition holds immutable provider information.
type ProviderDefinition struct {
WellKnown *WellKnown
JWKS *jose.JSONWebKeySet
}
// A ProviderError is returned for OIDC Provider errors.
type ProviderError struct {
Err error // The actual error
}
func wrapAsProviderError(err error) error {
if err == nil {
return nil
}
return &ProviderError{
Err: err,
}
}
func (e *ProviderError) Error() string {
return fmt.Sprintf("oidc provider error: %v", e.Err)
}
// These are the errors that can be returned in ProviderError.Err.
var (
ErrAllreadyInitialized = errors.New("already initialized")
ErrNotInitialized = errors.New("not initialized")
ErrWrongInitialization = errors.New("wrong initialization")
ErrIssuerMismatch = errors.New("issuer mismatch")
)
// NewProvider uses OpenID Connect discovery to create a Provider.
func NewProvider(issuer *url.URL, config *ProviderConfig) (*Provider, error) {
if config == nil {
config = DefaultProviderConfig
}
p := &Provider{
issuer: issuer.String(),
httpClient: config.HTTPClient,
httpHeader: config.HTTPHeader,
}
if config.WellKnownURI != nil {
p.wellKnownURI = config.WellKnownURI
} else {
relativeWellKnownURI, err := url.Parse(strings.TrimRight(issuer.Path, "/") + "/.well-known/openid-configuration")
if err != nil {
return nil, err
}
p.wellKnownURI = issuer.ResolveReference(relativeWellKnownURI)
}
if config.Logger != nil {
p.logger = config.Logger
} else {
p.logger = DefaultLogger
}
return p, nil
}
// Initialize initializes the associated Provider with the provided Context. If
// updates and/or errors channels apre provided, those channels receive any
// update or update error from the tasks resulting from the initialization. Any
// of thes channels can be nil, disabling the corresponding events being sent.
func (p *Provider) Initialize(ctx context.Context, updates chan *ProviderDefinition, errors chan error) error {
p.mutex.Lock()
if p.initialized {
p.mutex.Unlock()
return wrapAsProviderError(ErrAllreadyInitialized)
}
c, cancel := context.WithCancel(ctx)
p.cancel = cancel
p.initialized = true
started := make(chan error, 1)
p.started = started
go p.start(c, started, updates, errors)
p.mutex.Unlock()
err := <-started
return wrapAsProviderError(err)
}
// Shutdown stops the associated Provider and waits for it to do so.
func (p *Provider) Shutdown() error {
p.mutex.Lock()
defer p.mutex.Unlock()
if !p.initialized {
return wrapAsProviderError(ErrNotInitialized)
}
p.cancel()
err := <-p.started
p.cancel = nil
p.started = nil
p.initialized = false
p.ready = nil
if err == context.Canceled {
return nil
}
return wrapAsProviderError(err)
}
// Ready returns a channel that's closed when the associated Provider is ready.
func (p *Provider) Ready() <-chan struct{} {
p.mutex.RLock()
ready := p.ready
p.mutex.RUnlock()
return ready
}
func (p *Provider) start(ctx context.Context, started chan error, updates chan *ProviderDefinition, errors chan error) {
p.mutex.Lock()
if !p.initialized || started != p.started {
p.mutex.Unlock()
started <- ErrWrongInitialization
return
}
readystate := false
ready := make(chan struct{})
p.ready = ready
p.mutex.Unlock()
started <- nil
var wellKnown *WellKnown
var jwks *jose.JSONWebKeySet
var ignore error
dLoad := true
dUpdated := false
dExpireTimer := timer.NewTimer(DefaultJSONFetchExpiry)
kLoad := true
kUpdated := false
kExpireTimer := timer.NewTimer(DefaultJSONFetchExpiry)
for {
ignore = nil
dUpdated = false
kUpdated = false
if dLoad {
dst := WellKnown{}
p.logger.Printf("fetching OIDC provider discover document: %v\n", p.wellKnownURI)
expires, err := fetchJSON(ctx, p.wellKnownURI, &dst, p.httpClient, p.httpHeader)
if err != nil {
ignore = fmt.Errorf("failed to fetch discover document: %v", err)
if errors == nil {
p.logger.Printf("OIDC provider %v\n", ignore)
}
} else {
wellKnown = &dst
dUpdated = true
}
dLoad = false
dExpireTimer.Reset(expires)
p.logger.Printf("ODIC provider discover document loaded, expires: %v\n", expires)
}
if wellKnown != nil && kLoad {
dst := jose.JSONWebKeySet{}
if wellKnown.JwksURI != "" {
jwksURI, err := url.Parse(wellKnown.JwksURI)
if err != nil {
ignore = fmt.Errorf("discover document invalid jwks_uri: %v", err)
if errors == nil {
p.logger.Printf("OIDC provider %v\n", ignore)
}
} else {
p.logger.Printf("fetching OIDC provider jwks: %v", wellKnown.JwksURI)
expires, err := fetchJSON(ctx, jwksURI, &dst, p.httpClient, p.httpHeader)
if err != nil {
ignore = fmt.Errorf("failed to fetch jwks: %v", err)
if errors == nil {
p.logger.Printf("OIDC provider %v\n", ignore)
}
} else {
jwks = &dst
kUpdated = true
}
kLoad = false
kExpireTimer.Reset(expires)
p.logger.Printf("OIDC provider jwks loaded, expires: %v\n", expires)
}
}
}
p.mutex.Lock()
if dUpdated {
if wellKnown.Issuer != p.issuer {
if errors == nil {
p.logger.Printf("OIDC provider issuer mismatch: %v != %v\n", wellKnown.Issuer, p.issuer)
}
ignore = ErrIssuerMismatch
}
if ignore == nil {
p.logger.Printf("OIDC provider discover document updated\n")
p.wellKnown = wellKnown
}
}
if kUpdated {
if ignore == nil {
p.logger.Printf("ODIC provider jwks updated\n")
p.jwks = jwks
}
}
p.mutex.Unlock()
if updates != nil && ignore == nil && (dUpdated || kUpdated) {
p.logger.Printf("OIDC provider triggering update")
updates <- &ProviderDefinition{
WellKnown: wellKnown,
JWKS: jwks,
}
} else if errors != nil && ignore != nil {
p.logger.Printf("OIDC provider triggering errors")
errors <- wrapAsProviderError(ignore)
}
if !readystate {
if p.wellKnown != nil && p.jwks != nil {
readystate = true
close(ready)
}
}
select {
case <-ctx.Done():
started <- ctx.Err()
return
case <-dExpireTimer.C:
dLoad = true
case <-kExpireTimer.C:
kLoad = true
}
}
}
+28
View File
@@ -0,0 +1,28 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
const (
// ScopeOpenID is the string value of the base OIDC scope.
ScopeOpenID = "openid"
// ScopeProfile is the string value of the OIDC profile scope.
ScopeProfile = "profile"
// ScopeEmail is the string value of the OIDC email scope.
ScopeEmail = "email"
// ScopeOfflineAccess is the string value of the OIDC offline_access scope.
ScopeOfflineAccess = "offline_access"
)
+23
View File
@@ -0,0 +1,23 @@
/*
* Copyright 2017 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
const (
// SubjectIDPublic is the the string value of the Subject Identifier Type
// as defined in https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
SubjectIDPublic = "public"
)
+26
View File
@@ -0,0 +1,26 @@
/*
* Copyright 2017-2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// TokenTypeBearer is required for OIDC as defined in http://openid.net/specs/openid-connect-core-1_0.html.
const TokenTypeBearer = "Bearer"
// Token header as used in JSON web tokens.
const (
JWTHeaderKeyID = "kid"
JWTHeaderAlg = "alg"
)
+45
View File
@@ -0,0 +1,45 @@
/*
* Copyright 2019 Kopano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oidc
// WellKnown defines the OpenID Connect 1.0 discovery provider meta data as
// specified at https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
type WellKnown struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserInfoEndpoint string `json:"userinfo_endpoint"`
EndSessionEndpoint string `json:"end_session_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
CheckSessionIframe string `json:"check_session_iframe,omitempty"`
JwksURI string `json:"jwks_uri"`
ScopesSupported []string `json:"scopes_supported"`
ResponseTypesSupported []string `json:"response_types_supported"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
UserInfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported"`
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported"`
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
ClaimsSupported []string `json:"claims_supported"`
RequestParameterSupported bool `json:"request_parameter_supported"`
RequestURIParameterSupported bool `json:"request_uri_parameter_supported"`
}