Fetch of authorization token 50/7950/2
authorPatrikBuhr <patrik.buhr@est.tech>
Thu, 10 Mar 2022 15:07:56 +0000 (16:07 +0100)
committerPatrikBuhr <patrik.buhr@est.tech>
Wed, 16 Mar 2022 08:18:43 +0000 (09:18 +0100)
Signed-off-by: PatrikBuhr <patrik.buhr@est.tech>
Issue-ID: NONRTRIC-735
Change-Id: I3b012fda486820ee1967e89dfa0b0e573255751f

15 files changed:
auth-token-fetch/.gitignore [new file with mode: 0644]
auth-token-fetch/Dockerfile [new file with mode: 0644]
auth-token-fetch/HTTPClient.go [new file with mode: 0644]
auth-token-fetch/HTTPClient_test.go [new file with mode: 0644]
auth-token-fetch/LICENSE.txt [new file with mode: 0644]
auth-token-fetch/config.go [new file with mode: 0644]
auth-token-fetch/config_test.go [new file with mode: 0644]
auth-token-fetch/container-tag.yaml [new file with mode: 0644]
auth-token-fetch/go.mod [new file with mode: 0644]
auth-token-fetch/go.sum [new file with mode: 0644]
auth-token-fetch/main.go [new file with mode: 0644]
auth-token-fetch/main_test.go [new file with mode: 0644]
auth-token-fetch/run-tests-ubuntu.sh [new file with mode: 0755]
auth-token-fetch/security/tls.crt [new file with mode: 0644]
auth-token-fetch/security/tls.key [new file with mode: 0644]

diff --git a/auth-token-fetch/.gitignore b/auth-token-fetch/.gitignore
new file mode 100644 (file)
index 0000000..d75b8ae
--- /dev/null
@@ -0,0 +1,5 @@
+.history
+.vscode
+coverage.*
+__debug_bin*
+
diff --git a/auth-token-fetch/Dockerfile b/auth-token-fetch/Dockerfile
new file mode 100644 (file)
index 0000000..e8d4c34
--- /dev/null
@@ -0,0 +1,38 @@
+#==================================================================================
+#   Copyright (C) 2022: Nordix Foundation
+#
+#   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.
+#
+#   This source code is part of the non-RT RIC (RAN Intelligent Controller)
+#==================================================================================
+
+##
+## Build
+##
+FROM nexus3.o-ran-sc.org:10001/golang:1.17-bullseye AS build
+WORKDIR /app
+COPY go.mod .
+COPY go.sum .
+RUN go mod download
+COPY . .
+RUN go build -o /auth-token-fetch
+##
+## Deploy
+##
+FROM gcr.io/distroless/base-debian11
+WORKDIR /
+## Copy from "build" stage
+COPY --from=build /auth-token-fetch .
+COPY --from=build /app/security/* /security/
+USER nonroot:nonroot
+ENTRYPOINT ["/auth-token-fetch"]
diff --git a/auth-token-fetch/HTTPClient.go b/auth-token-fetch/HTTPClient.go
new file mode 100644 (file)
index 0000000..ab76b13
--- /dev/null
@@ -0,0 +1,106 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "bytes"
+       "crypto/tls"
+       "fmt"
+       "io"
+
+       "net/http"
+       "net/url"
+       "time"
+)
+
+// HTTPClient interface
+type HTTPClient interface {
+       Get(url string) (*http.Response, error)
+
+       Do(*http.Request) (*http.Response, error)
+}
+
+func CreateHttpClient(cert tls.Certificate, timeout time.Duration) *http.Client {
+       return &http.Client{
+               Timeout:   timeout,
+               Transport: createTransport(cert),
+       }
+}
+
+type RequestError struct {
+       StatusCode int
+       Body       []byte
+}
+
+func (pe RequestError) Error() string {
+       return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
+}
+
+func Post(url string, body []byte, contentType string, client HTTPClient) error {
+       return do(http.MethodPost, url, body, contentType, client)
+}
+
+func do(method string, url string, body []byte, contentType string, client HTTPClient) error {
+       if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
+               req.Header.Set("Content-Type", contentType)
+               if response, respErr := client.Do(req); respErr == nil {
+                       if isResponseSuccess(response.StatusCode) {
+                               return nil
+                       } else {
+                               return getRequestError(response)
+                       }
+               } else {
+                       return respErr
+               }
+       } else {
+               return reqErr
+       }
+}
+
+func isResponseSuccess(statusCode int) bool {
+       return statusCode >= http.StatusOK && statusCode <= 299
+}
+
+func getRequestError(response *http.Response) RequestError {
+       defer response.Body.Close()
+       responseData, _ := io.ReadAll(response.Body)
+       putError := RequestError{
+               StatusCode: response.StatusCode,
+               Body:       responseData,
+       }
+       return putError
+}
+
+func createTransport(cert tls.Certificate) *http.Transport {
+       return &http.Transport{
+               TLSClientConfig: &tls.Config{
+                       Certificates: []tls.Certificate{
+                               cert,
+                       },
+                       InsecureSkipVerify: true,
+               },
+       }
+}
+
+func IsUrlSecure(configUrl string) bool {
+       u, _ := url.Parse(configUrl)
+       return u.Scheme == "https"
+}
diff --git a/auth-token-fetch/HTTPClient_test.go b/auth-token-fetch/HTTPClient_test.go
new file mode 100644 (file)
index 0000000..e0a4cd1
--- /dev/null
@@ -0,0 +1,59 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "crypto/tls"
+
+       "net/http"
+       "reflect"
+       "testing"
+       "time"
+
+       "github.com/stretchr/testify/require"
+)
+
+func TestRequestError_Error(t *testing.T) {
+       assertions := require.New(t)
+       actualError := RequestError{
+               StatusCode: http.StatusBadRequest,
+               Body:       []byte("error"),
+       }
+       assertions.Equal("Request failed due to error response with status: 400 and body: error", actualError.Error())
+}
+
+func Test_CreateClient(t *testing.T) {
+       assertions := require.New(t)
+
+       client := CreateHttpClient(tls.Certificate{}, 5*time.Second)
+
+       transport := client.Transport
+       assertions.Equal("*http.Transport", reflect.TypeOf(transport).String())
+       assertions.Equal(5*time.Second, client.Timeout)
+}
+
+func TestIsUrlSecured(t *testing.T) {
+       assertions := require.New(t)
+
+       assertions.True(IsUrlSecure("https://url"))
+
+       assertions.False(IsUrlSecure("http://url"))
+}
diff --git a/auth-token-fetch/LICENSE.txt b/auth-token-fetch/LICENSE.txt
new file mode 100644 (file)
index 0000000..96589bf
--- /dev/null
@@ -0,0 +1,201 @@
+                                 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. 
diff --git a/auth-token-fetch/config.go b/auth-token-fetch/config.go
new file mode 100644 (file)
index 0000000..18d610d
--- /dev/null
@@ -0,0 +1,100 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "os"
+
+       "strconv"
+
+       "fmt"
+
+       log "github.com/sirupsen/logrus"
+)
+
+type Config struct {
+       LogLevel                log.Level
+       CertPath                string
+       KeyPath                 string
+       AuthServiceUrl          string
+       GrantType               string
+       ClientSecret            string
+       ClientId                string
+       AuthTokenOutputFileName string
+       RefreshMarginSeconds    int
+}
+
+func NewConfig() *Config {
+       return &Config{
+               CertPath:                getEnv("CERT_PATH", "security/tls.crt"),
+               KeyPath:                 getEnv("CERT_KEY_PATH", "security/tls.key"),
+               LogLevel:                getLogLevel(),
+               GrantType:               getEnv("CREDS_GRANT_TYPE", ""),
+               ClientSecret:            getEnv("CREDS_CLIENT_SECRET", ""),
+               ClientId:                getEnv("CREDS_CLIENT_ID", ""),
+               AuthTokenOutputFileName: getEnv("OUTPUT_FILE", "/tmp/authToken.txt"),
+               AuthServiceUrl:          getEnv("AUTH_SERVICE_URL", "https://localhost:39687/example-singlelogin-sever/login"),
+               RefreshMarginSeconds:    getEnvAsInt("REFRESH_MARGIN_SECONDS", 5, 1, 3600),
+       }
+}
+
+func validateConfiguration(configuration *Config) error {
+       if configuration.CertPath == "" || configuration.KeyPath == "" {
+               return fmt.Errorf("missing CERT_PATH and/or CERT_KEY_PATH")
+       }
+
+       return nil
+}
+
+func getEnv(key string, defaultVal string) string {
+       if value, exists := os.LookupEnv(key); exists {
+               log.Debugf("Using value: '%v' for '%v'", value, key)
+               return value
+       } else {
+               log.Debugf("Using default value: '%v' for '%v'", defaultVal, key)
+               return defaultVal
+       }
+}
+
+func getEnvAsInt(name string, defaultVal int, min int, max int) int {
+       valueStr := getEnv(name, "")
+       if value, err := strconv.Atoi(valueStr); err == nil {
+               if value < min || value > max {
+                       log.Warnf("Value out of range: '%v' for variable: '%v'. Default value: '%v' will be used", valueStr, name, defaultVal)
+                       return defaultVal
+               }
+               return value
+       } else if valueStr != "" {
+               log.Warnf("Invalid int value: '%v' for variable: '%v'. Default value: '%v' will be used", valueStr, name, defaultVal)
+       }
+       return defaultVal
+
+}
+
+func getLogLevel() log.Level {
+       logLevelStr := getEnv("LOG_LEVEL", "Info")
+       if loglevel, err := log.ParseLevel(logLevelStr); err == nil {
+               return loglevel
+       } else {
+               log.Warnf("Invalid log level: %v. Log level will be Info!", logLevelStr)
+               return log.InfoLevel
+       }
+}
diff --git a/auth-token-fetch/config_test.go b/auth-token-fetch/config_test.go
new file mode 100644 (file)
index 0000000..8b441c1
--- /dev/null
@@ -0,0 +1,60 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "os"
+       "testing"
+
+       log "github.com/sirupsen/logrus"
+       "github.com/stretchr/testify/require"
+)
+
+func TestNew_envVarsSetConfigContainSetValues(t *testing.T) {
+       assertions := require.New(t)
+       os.Setenv("LOG_LEVEL", "Debug")
+       os.Setenv("CERT_PATH", "CERT_PATH")
+       os.Setenv("CERT_KEY_PATH", "CERT_KEY_PATH")
+       os.Setenv("CREDS_GRANT_TYPE", "CREDS_GRANT_TYPE")
+       os.Setenv("CREDS_CLIENT_SECRET", "CREDS_CLIENT_SECRET")
+       os.Setenv("CREDS_CLIENT_ID", "CREDS_CLIENT_ID")
+       os.Setenv("OUTPUT_FILE", "OUTPUT_FILE")
+       os.Setenv("AUTH_SERVICE_URL", "AUTH_SERVICE_URL")
+       os.Setenv("REFRESH_MARGIN_SECONDS", "33")
+
+       t.Cleanup(func() {
+               os.Clearenv()
+       })
+       wantConfig := Config{
+               LogLevel:                log.DebugLevel,
+               CertPath:                "CERT_PATH",
+               KeyPath:                 "CERT_KEY_PATH",
+               AuthServiceUrl:          "AUTH_SERVICE_URL",
+               GrantType:               "CREDS_GRANT_TYPE",
+               ClientSecret:            "CREDS_CLIENT_SECRET",
+               ClientId:                "CREDS_CLIENT_ID",
+               AuthTokenOutputFileName: "OUTPUT_FILE",
+               RefreshMarginSeconds:    33,
+       }
+       got := NewConfig()
+
+       assertions.Equal(&wantConfig, got)
+}
diff --git a/auth-token-fetch/container-tag.yaml b/auth-token-fetch/container-tag.yaml
new file mode 100644 (file)
index 0000000..f84eeb1
--- /dev/null
@@ -0,0 +1,5 @@
+# The Jenkins job requires a tag to build the Docker image.
+# By default this file is in the docker build directory,
+# but the location can configured in the JJB template.
+---
+tag: 1.1.0
diff --git a/auth-token-fetch/go.mod b/auth-token-fetch/go.mod
new file mode 100644 (file)
index 0000000..b1fd1b6
--- /dev/null
@@ -0,0 +1,17 @@
+module oransc.org/nonrtric/auth-token-fetch
+
+go 1.17
+
+require (
+       github.com/sirupsen/logrus v1.8.1
+       github.com/stretchr/testify v1.7.0
+)
+
+require (
+       github.com/davecgh/go-spew v1.1.1 // indirect
+       github.com/kr/pretty v0.2.0 // indirect
+       github.com/pmezard/go-difflib v1.0.0 // indirect
+       golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 // indirect
+       gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
+       gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
+)
diff --git a/auth-token-fetch/go.sum b/auth-token-fetch/go.sum
new file mode 100644 (file)
index 0000000..f638fbf
--- /dev/null
@@ -0,0 +1,24 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/kr/pretty v0.2.0 h1:s5hAObm+yFO5uHYt5dYjxi2rXrsnmRpJx4OYvIWUaQs=
+github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
+github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
+github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
+github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
+github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y=
+golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
+gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/auth-token-fetch/main.go b/auth-token-fetch/main.go
new file mode 100644 (file)
index 0000000..9a63534
--- /dev/null
@@ -0,0 +1,157 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "crypto/tls"
+       "encoding/json"
+       "fmt"
+       "io/ioutil"
+       "net/http"
+       "net/url"
+       "time"
+
+       "os"
+
+       log "github.com/sirupsen/logrus"
+)
+
+type JwtToken struct {
+       Access_token string
+       Expires_in   int
+       Token_type   string
+}
+
+type Context struct {
+       Running bool
+       Config  *Config
+}
+
+func NewContext(config *Config) *Context {
+       return &Context{
+               Running: true,
+               Config:  config,
+       }
+}
+
+// @title Auth token fetcher
+// @version 0.0.0
+
+// @license.name  Apache 2.0
+// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html
+
+func main() {
+       configuration := NewConfig()
+       log.SetLevel(configuration.LogLevel)
+
+       log.Debug("Using configuration: ", configuration)
+       start(NewContext(configuration))
+
+       keepAlive()
+}
+
+func start(context *Context) {
+       log.Debug("Initializing")
+       if err := validateConfiguration(context.Config); err != nil {
+               log.Fatalf("Stopping due to error: %v", err)
+       }
+
+       var cert tls.Certificate
+       if c, err := loadCertificate(context.Config.CertPath, context.Config.KeyPath); err == nil {
+               cert = c
+       } else {
+               log.Fatalf("Stopping due to error: %v", err)
+       }
+
+       webClient := CreateHttpClient(cert, 10*time.Second)
+
+       go periodicRefreshIwtToken(webClient, context)
+}
+
+func periodicRefreshIwtToken(webClient *http.Client, context *Context) {
+       for context.Running {
+               jwtToken, err := fetchJwtToken(webClient, context.Config)
+               if check(err) {
+                       saveAccessToken(jwtToken, context.Config)
+               }
+               delayTime := calcDelayTime(jwtToken, err, context.Config)
+               log.WithFields(log.Fields{"seconds": delayTime.Seconds()}).Debug("Sleeping")
+               time.Sleep(delayTime)
+       }
+}
+
+func calcDelayTime(token JwtToken, e error, confing *Config) time.Duration {
+       if e != nil {
+               return time.Second * 1
+       }
+       remains := token.Expires_in - confing.RefreshMarginSeconds
+       if remains < 1 {
+               remains = 1
+       }
+       return time.Second * time.Duration(remains)
+}
+
+func check(e error) bool {
+       if e != nil {
+               log.Errorf("Failure reason: %v", e)
+               return false
+       }
+       return true
+}
+
+func saveAccessToken(token JwtToken, configuration *Config) {
+       log.WithFields(log.Fields{"file": configuration.AuthTokenOutputFileName}).Debug("Saving access token")
+       data := []byte(token.Access_token)
+       err := os.WriteFile(configuration.AuthTokenOutputFileName, data, 0644)
+       check(err)
+}
+
+func fetchJwtToken(webClient *http.Client, configuration *Config) (JwtToken, error) {
+       log.WithFields(log.Fields{"url": configuration.AuthServiceUrl}).Debug("Fetching token")
+       var jwt JwtToken
+       var err error
+       resp, err := webClient.PostForm(configuration.AuthServiceUrl,
+               url.Values{"client_secret": {configuration.ClientSecret}, "grant_type": {configuration.GrantType}, "client_id": {configuration.ClientId}})
+
+       if check(err) {
+               var body []byte
+               defer resp.Body.Close()
+               body, err = ioutil.ReadAll(resp.Body)
+               if check(err) {
+                       err = json.Unmarshal([]byte(body), &jwt)
+               }
+       }
+       return jwt, err
+}
+
+func loadCertificate(certPath string, keyPath string) (tls.Certificate, error) {
+       log.WithFields(log.Fields{"certPath": certPath, "keyPath": keyPath}).Debug("Loading cert")
+       if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
+               return cert, nil
+       } else {
+               return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
+       }
+}
+
+func keepAlive() {
+       channel := make(chan int)
+       <-channel
+}
diff --git a/auth-token-fetch/main_test.go b/auth-token-fetch/main_test.go
new file mode 100644 (file)
index 0000000..1b0a87e
--- /dev/null
@@ -0,0 +1,158 @@
+// -
+//   ========================LICENSE_START=================================
+//   O-RAN-SC
+//   %%
+//   Copyright (C) 2022: Nordix Foundation
+//   %%
+//   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.
+//   ========================LICENSE_END===================================
+//
+
+package main
+
+import (
+       "bytes"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "io/ioutil"
+       "net/http"
+       "os"
+       "sync"
+       "testing"
+       "time"
+
+       log "github.com/sirupsen/logrus"
+       "github.com/stretchr/testify/require"
+)
+
+func createHttpClientMock(t *testing.T, configuration *Config, wg *sync.WaitGroup, token JwtToken) *http.Client {
+       assertions := require.New(t)
+       clientMock := NewTestClient(func(req *http.Request) *http.Response {
+               if req.URL.String() == configuration.AuthServiceUrl {
+                       assertions.Equal(req.Method, "POST")
+                       body := getBodyAsString(req, t)
+                       assertions.Contains(body, "client_id="+configuration.ClientId)
+                       assertions.Contains(body, "secret="+configuration.ClientSecret)
+                       assertions.Contains(body, "grant_type="+configuration.GrantType)
+                       contentType := req.Header.Get("content-type")
+                       assertions.Equal("application/x-www-form-urlencoded", contentType)
+                       wg.Done()
+                       return &http.Response{
+                               StatusCode: 200,
+                               Body:       ioutil.NopCloser(bytes.NewBuffer(toBody(token))),
+                               Header:     make(http.Header), // Must be set to non-nil value or it panics
+                       }
+               }
+               t.Error("Wrong call to client: ", req)
+               t.Fail()
+               return nil
+       })
+       return clientMock
+}
+
+func TestFetchAndStoreToken(t *testing.T) {
+       log.SetLevel(log.TraceLevel)
+       assertions := require.New(t)
+       configuration := NewConfig()
+       configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
+       configuration.ClientId = "testClientId"
+       configuration.ClientSecret = "testClientSecret"
+       context := NewContext(configuration)
+
+       t.Cleanup(func() {
+               os.Remove(configuration.AuthTokenOutputFileName)
+       })
+
+       accessToken := "Access_token" + fmt.Sprint(time.Now().UnixNano())
+       token := JwtToken{Access_token: accessToken, Expires_in: 10, Token_type: "Token_type"}
+
+       wg := sync.WaitGroup{}
+       wg.Add(2) // Get token two times
+       clientMock := createHttpClientMock(t, configuration, &wg, token)
+
+       go periodicRefreshIwtToken(clientMock, context)
+
+       if waitTimeout(&wg, 7*time.Second) {
+               t.Error("Not all calls to server were made")
+               t.Fail()
+       }
+
+       tokenFileContent, err := ioutil.ReadFile(configuration.AuthTokenOutputFileName)
+       check(err)
+
+       assertions.Equal(accessToken, string(tokenFileContent))
+
+       context.Running = false
+}
+
+func TestStart(t *testing.T) {
+       assertions := require.New(t)
+       log.SetLevel(log.TraceLevel)
+
+       configuration := NewConfig()
+       configuration.AuthTokenOutputFileName = "/tmp/authToken" + fmt.Sprint(time.Now().UnixNano())
+       context := NewContext(configuration)
+
+       start(context)
+
+       time.Sleep(time.Second * 5)
+
+       _, err := os.Stat(configuration.AuthTokenOutputFileName)
+
+       assertions.True(errors.Is(err, os.ErrNotExist))
+       context.Running = false
+}
+
+func toBody(token JwtToken) []byte {
+       body, err := json.Marshal(token)
+       check(err)
+       return body
+}
+
+type RoundTripFunc func(req *http.Request) *http.Response
+
+func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+       return f(req), nil
+}
+
+//NewTestClient returns *http.Client with Transport replaced to avoid making real calls
+func NewTestClient(fn RoundTripFunc) *http.Client {
+       return &http.Client{
+               Transport: RoundTripFunc(fn),
+       }
+}
+
+// waitTimeout waits for the waitgroup for the specified max timeout.
+// Returns true if waiting timed out.
+func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
+       c := make(chan struct{})
+       go func() {
+               defer close(c)
+               wg.Wait()
+       }()
+       select {
+       case <-c:
+               return false // completed normally
+       case <-time.After(timeout):
+               return true // timed out
+       }
+}
+
+func getBodyAsString(req *http.Request, t *testing.T) string {
+       buf := new(bytes.Buffer)
+       if _, err := buf.ReadFrom(req.Body); err != nil {
+               t.Fail()
+       }
+       return buf.String()
+}
diff --git a/auth-token-fetch/run-tests-ubuntu.sh b/auth-token-fetch/run-tests-ubuntu.sh
new file mode 100755 (executable)
index 0000000..f7de28b
--- /dev/null
@@ -0,0 +1,42 @@
+#!/bin/bash
+##############################################################################
+#
+#   Copyright (C) 2022: Nordix Foundation
+#
+#   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.
+#
+##############################################################################
+SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
+set -eux
+
+echo "--> $0"
+curdir=`pwd`
+# go installs tools like go-acc to $HOME/go/bin
+# ubuntu minion path lacks go
+export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin
+go version
+cd $SCRIPT_DIR
+
+# install the go coverage tool helper
+go get -v github.com/ory/go-acc
+export GO111MODULE=on
+go get github.com/stretchr/testify/mock@v1.7.0
+
+go mod vendor 
+
+go-acc ./... --ignore mocks
+
+go mod tidy 
+
+echo "--> $0 ends"
diff --git a/auth-token-fetch/security/tls.crt b/auth-token-fetch/security/tls.crt
new file mode 100644 (file)
index 0000000..0f6d8a3
--- /dev/null
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDXzCCAkegAwIBAgIUEbuDTP0ixwxCxCQ9tR5DijGCbtkwDQYJKoZIhvcNAQEL
+BQAwPzELMAkGA1UEBhMCc2UxDDAKBgNVBAoMA0VTVDERMA8GA1UECwwIRXJpY3Nz
+b24xDzANBgNVBAMMBnNlcnZlcjAeFw0yMTEwMTkxNDA1MzVaFw0zMTEwMTcxNDA1
+MzVaMD8xCzAJBgNVBAYTAnNlMQwwCgYDVQQKDANFU1QxETAPBgNVBAsMCEVyaWNz
+c29uMQ8wDQYDVQQDDAZzZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQDnH4imV8kx/mXz6BDbq8e4oZGqGgv7V837iNspj/zIZXhEMP9311fdsZEE
+Y6VWU47bSYRn2xJOP+wmfKewbw0OcEWu/RkdvO7Y0VIVrlbEJYu88ZjK14dMUpfe
+72iMbTc5q2uYi0ImB5/m3jyMSXgso6NDWuvXrp2VSWjb1tG++des9rhvyrZyNrua
+I4iOnMvvuc71gvHol7appRu3+LRTQFYsAizdfHEQ9k949MZH4fiIu5NmCT/wNJVo
+uUZYYJseFhOlIANaXn6qmz7kKVYfxfV+Z5EccaRixaClCFwyRdmjgLyyeuI4/QPD
+x9PjmGmf6eOEC2ZHBi4OHwjIzmLnAgMBAAGjUzBRMB0GA1UdDgQWBBRjeDLPpLm2
+W623wna7xBCbHxtxVjAfBgNVHSMEGDAWgBRjeDLPpLm2W623wna7xBCbHxtxVjAP
+BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAbFUAWFZaIMXmd5qv/
+xJYr1oPJpsmbgWGRWZWDZqbUabvWObyXlDJWIau60BerfcC5TmyElBjTyONSGwCT
+tq+SVB0PXpgqa8ZQ25Ytn2AMDFWhrGbOefCXs6te3HGq6BNubTWrOVIvJypCwC95
++iXVuDd4eg+n2fWv7h7fZRZHum/zLoRxB2lKoMMbc/BQX9hbtP6xyvIVvaYdhcJw
+VzJJGIDqpMiMH6IBaOFSmgfOyGblGKAicj3E3kpGBfadLx3R+9V6aG7zyBnVbr2w
+YJbV2Ay4PrF+PTpCMB/mNwC5RBTYHpSNdrCMSyq3I+QPVJq8dPJr7fd1Uwl3WHqX
+FV0h
+-----END CERTIFICATE-----
diff --git a/auth-token-fetch/security/tls.key b/auth-token-fetch/security/tls.key
new file mode 100644 (file)
index 0000000..5346bb7
--- /dev/null
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnH4imV8kx/mXz
+6BDbq8e4oZGqGgv7V837iNspj/zIZXhEMP9311fdsZEEY6VWU47bSYRn2xJOP+wm
+fKewbw0OcEWu/RkdvO7Y0VIVrlbEJYu88ZjK14dMUpfe72iMbTc5q2uYi0ImB5/m
+3jyMSXgso6NDWuvXrp2VSWjb1tG++des9rhvyrZyNruaI4iOnMvvuc71gvHol7ap
+pRu3+LRTQFYsAizdfHEQ9k949MZH4fiIu5NmCT/wNJVouUZYYJseFhOlIANaXn6q
+mz7kKVYfxfV+Z5EccaRixaClCFwyRdmjgLyyeuI4/QPDx9PjmGmf6eOEC2ZHBi4O
+HwjIzmLnAgMBAAECggEBAMq1lZyPkh8PCUyLVX3VhC4jRybyAWBI+piKx+4EI6l/
+laP5dZcegCoo+w/mdbTpRHqAWGjec4e9+Nkoq8rLG6B2SCfaRJUYiEQSEvSBHAid
+BZqKK4B82GXQavNU91Vy1OT3vD7mpPXF6jEK6gAA0C4Wt7Lzo7ZfqEavRBDMsNnV
+jOxLwWJCFSKhfeA6grJCnagmEDKSxxazlNBgCahjPf/+IRJZ7Vk4Zjq+I/5nWKf8
+lYaQExKDIANuM/jMRnYVq5k4g2MKHUADWGTSvG1DMJiMHzdxb2miZovpIkEE86bC
+wKBuele9IR6Rb/wygYj7WdaWysZ081OT7mNyju08e4ECgYEA8+q7vv4Nlz8bAcmY
+Ip5517s15M5D9iLsE2Q5m9Zs99rUyQv0E8ekpChhtTSdvj+eNl39O4hji46Gyceu
+MYPfNL7+YWaFDxuyaXEe/OFuKbFqgE1p08HXFcQJCvgqD1MWO5b9BRDc0qpNFIA8
+eN9xFBMQ2UFaALBMAup7Ef85q4kCgYEA8pKOAIsgmlnO8P9cPzkMC1oozslraAti
+1JnOJjwPLoHFubtH2u7WoIkSvNfeNwfrsVXwAP0m7C8p7qhYppS+0XGjKpYNSezK
+1GCqCVv8R1m+AsSseSUUaQCmEydd+gQbBq3r4u3wU3ylrgAoR3m+7SVyhvD+vbwI
+7+zfj+O3zu8CgYEAqaAsQH5c5Tm1hmCztB+RjD1dFWl8ScevdSzWA1HzJcrA/6+Y
+ZckI7kBG8sVMjemgFR735FbNI1hS1DBRK44Rw5SvQv0Qu5j/UeShMCt1ePkwn1k2
+p1S+Rxy1TTOXzGBzra0q+ELpzncwc3lalJSPBu7bYLrZ5HC167E1NSbQ7EECgYBo
+e/IIj+TyNz7pFcVhQixK84HiWGYYQddHJhzi4TnU2XcWonG3/uqZ6ZEVoJIJ+DJw
+h0jC1EggscwJDaBp2GY9Bwq2PD3rGsDfK+fx8ho/jYtH2/lCkVMyS2I9m9Zh68TM
+YrvZWo4LGASxZ0XyS6GOunOTZlkD1uuulMRTUU4KJwKBgQCwyjs0/ElVFvO0lPIC
+JJ//B5rqI7hNMJuTBvr4yiqVZdbgFukaU7FBVyNYDMpZi/nRbpglm+psFcwXtL8n
+bHOIGLkh8vB7OuETRYhXs567lPYtO4BmHZlXW70Sq/0xqi/Mmz1RuEg4SQ1Ug5oy
+wG6IV5EWSQAhsGirdybQ+bY7Kw==
+-----END PRIVATE KEY-----