Skip to content

Commit

Permalink
fix: security fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
karl-cardenas-coding committed Aug 18, 2024
1 parent 576e907 commit f16acbc
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 8 deletions.
82 changes: 82 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
name: "CodeQL"

on:
push:
branches: [ "main", "default" ]
pull_request:
branches: [ "main", "default" ]
schedule:
- cron: '18 5 * * 6'

jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
# required for all workflows
security-events: write

# required to fetch internal or private CodeQL packs
packages: read

# only required for workflows in private repositories
actions: read
contents: read

strategy:
fail-fast: false
matrix:
include:
- language: go
build-mode: autobuild
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.

# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality

# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
1 change: 1 addition & 0 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @karl-cardenas-coding
22 changes: 19 additions & 3 deletions cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,11 @@ func login() error {
TokenURL: internal.DEFAULT_ACCESS_TOKEN_URL,
},
}

state := internal.GenerateStateOauthCookie()

slog.Debug("Redirect Config", "URL:", "http://localhost:"+port+redirectURL)
authUrl := internal.GetAuthURL(*config)
authUrl := internal.GetAuthURL(*config, state)

if authUrl == "" {
return errors.New("unable to get authentication URL. Please check the client ID and client secret are correct")
Expand All @@ -113,7 +116,7 @@ func login() error {
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", landingPageHandler(GlobalStaticAssets, "web/index.html", authUrl))
http.HandleFunc("/close", closeHandler)
http.HandleFunc("/redirect", redirectHandler(GlobalStaticAssets, "web/redirect.html", "web/error.html", config, cliCfg.Credentials.CredentialsFile))
http.HandleFunc("/redirect", redirectHandler(GlobalStaticAssets, "web/redirect.html", "web/error.html", config, state, cliCfg.Credentials.CredentialsFile))

slog.Info("Listening on port 8080. Visit http://localhost:8080 to autenticate with the Whoop API and get an access token.")
err = openBrowser("http://localhost:"+port, noAutoOpenBrowser)
Expand Down Expand Up @@ -152,12 +155,25 @@ func landingPageHandler(assets fs.FS, indexFile string, authUrl string) http.Han

// redirectHandler handles the redirect URL after authenticating with the Whoop API
// and writes the access token to a file
func redirectHandler(assets fs.FS, page, errorPage string, authConf *oauth2.Config, credentialsFilePath string) http.HandlerFunc {
func redirectHandler(assets fs.FS, page, errorPage string, authConf *oauth2.Config, stateIdentifier string, credentialsFilePath string) http.HandlerFunc {

return func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
slog.Debug("Code received", "code", code)

state := r.URL.Query().Get("state")

if state != stateIdentifier {
slog.Error("State does not match", "state", state)
err := sendErrorTemplate(w, "The unique authentication state identifier does not match the provided value from MyWhoop. You may be subject to a man-in-the-middle (MITM) attack.", http.StatusBadRequest, errorPage, assets)
if err != nil {
slog.Error("unable to send error template", "error", err)
}
return
}

slog.Debug("State received", "state", state)

if code == "" {
// slog.Info("no code received.", "Error response status: ", r.Response.StatusCode)
err := sendErrorTemplate(w, "No authorization code returned by the Whoop authorization server.", http.StatusInternalServerError, errorPage, assets)
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/karl-cardenas-coding/mywhoop

go 1.22
go 1.23

require (
github.com/aws/aws-sdk-go-v2/config v1.27.27
Expand Down
19 changes: 16 additions & 3 deletions internal/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ package internal

import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand All @@ -27,9 +29,8 @@ func getEndpoint() oauth2.Endpoint {
}

// GetAuthURL returns the URL to authenticate with the Whoop API
func GetAuthURL(auth oauth2.Config) string {

return auth.AuthCodeURL("stateidentifier", oauth2.AccessTypeOffline)
func GetAuthURL(auth oauth2.Config, state string) string {
return auth.AuthCodeURL(state, oauth2.AccessTypeOffline)
}

// GetAccessToken exchanges the access code returned from the authorization flow for an access token
Expand Down Expand Up @@ -158,3 +159,15 @@ func ReadTokenFromFile(filePath string) (oauth2.Token, error) {

return token, nil
}

// GenerateStateOauthCookie generates a random state string
func GenerateStateOauthCookie() string {
b := make([]byte, 128)
rand.Read(b)

Check failure on line 166 in internal/auth.go

View workflow job for this annotation

GitHub Actions / Lint

Error return value of `rand.Read` is not checked (errcheck)
// only do letters and numbers
randString := base64.URLEncoding.EncodeToString(b)
// Return 8 characters of the random string
state := randString[:12]

return state
}
11 changes: 10 additions & 1 deletion internal/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,8 @@ func TestGetAuthURL(t *testing.T) {

for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
authUrl := GetAuthURL(test.auth)

authUrl := GetAuthURL(test.auth, GenerateStateOauthCookie())

if authUrl == "" {
t.Errorf("%s: Expected a non-empty string but got an empty string", test.description)
Expand All @@ -606,3 +607,11 @@ func TestGetAuthURL(t *testing.T) {
})
}
}
func TestGenerateStateOauthCookie(t *testing.T) {
state := GenerateStateOauthCookie()

if len(state) == 0 {
t.Error("Failed to generate state cookie")
}

}

0 comments on commit f16acbc

Please sign in to comment.