diff options
| author | jwijenbergh <jeroenwijenbergh@protonmail.com> | 2022-11-24 15:40:39 +0100 |
|---|---|---|
| committer | jwijenbergh <jeroenwijenbergh@protonmail.com> | 2022-11-24 15:40:39 +0100 |
| commit | 8be555e5f91c6069c3d51cb014f1849fd182b1dc (patch) | |
| tree | 9c78f2ee1f5122da1e1ed3e452682f7f6744778f | |
| parent | 791fffebff4499e4fad3217e2160596e1b8b3eea (diff) | |
Style: Use stylecheck and fix errors
| -rw-r--r-- | .github/workflows/test.yml | 2 | ||||
| -rw-r--r-- | client/client.go | 10 | ||||
| -rw-r--r-- | client/client_test.go | 34 | ||||
| -rw-r--r-- | client/fsm.go | 246 | ||||
| -rw-r--r-- | client/server.go | 72 | ||||
| -rw-r--r-- | cmd/cli/main.go | 12 | ||||
| -rw-r--r-- | exports/disco.go | 2 | ||||
| -rw-r--r-- | exports/exports.go | 50 | ||||
| -rw-r--r-- | internal/discovery/discovery.go | 6 | ||||
| -rw-r--r-- | internal/fsm/fsm.go | 14 | ||||
| -rw-r--r-- | internal/http/http.go | 4 | ||||
| -rw-r--r-- | internal/log/log.go | 48 | ||||
| -rw-r--r-- | internal/oauth/oauth.go | 24 | ||||
| -rw-r--r-- | internal/server/api.go | 12 | ||||
| -rw-r--r-- | internal/server/common.go | 13 | ||||
| -rw-r--r-- | internal/server/custom.go | 6 | ||||
| -rw-r--r-- | internal/server/instituteaccess.go | 6 | ||||
| -rw-r--r-- | internal/server/secureinternet.go | 40 | ||||
| -rw-r--r-- | internal/util/util_test.go | 11 | ||||
| -rw-r--r-- | internal/verify/verify.go | 12 | ||||
| -rw-r--r-- | internal/wireguard/wireguard.go | 10 | ||||
| -rw-r--r-- | types/error.go | 10 | ||||
| -rw-r--r-- | types/server.go | 2 |
23 files changed, 323 insertions, 323 deletions
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8903107..b9fe694 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,6 +14,8 @@ jobs: - uses: actions/checkout@v3 - name: Run golangci-lint uses: golangci/golangci-lint-action@v3.2.0 + with: + args: ./... -E stylecheck test-go: name: Test Go diff --git a/client/client.go b/client/client.go index 63e4f91..6ef9a9f 100644 --- a/client/client.go +++ b/client/client.go @@ -77,7 +77,7 @@ func (client *Client) Register( debug bool, ) error { errorMessage := "failed to register with the GO library" - if !client.InFSMState(STATE_DEREGISTERED) { + if !client.InFSMState(StateDeregistered) { return client.handleError( errorMessage, FSMDeregisteredError{}.CustomError(), @@ -89,9 +89,9 @@ func (client *Client) Register( client.Language = language // Initialize the logger - logLevel := log.LOG_WARNING + logLevel := log.LogWarning if debug { - logLevel = log.LOG_DEBUG + logLevel = log.LogDebug } loggerErr := client.Logger.Init(logLevel, directory) @@ -118,7 +118,7 @@ func (client *Client) Register( } // Go to the No Server state with the saved servers after we're done - defer client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + defer client.FSM.GoTransitionWithData(StateNoServer, client.Servers) // Let's Connect! doesn't care about discovery if client.isLetsConnect() { @@ -160,7 +160,7 @@ func (client *Client) askProfile(chosenServer server.Server) error { if profilesErr != nil { return types.NewWrappedError(errorMessage, profilesErr) } - goTransitionErr := client.FSM.GoTransitionRequired(STATE_ASK_PROFILE, profiles) + goTransitionErr := client.FSM.GoTransitionRequired(StateAskProfile, profiles) if goTransitionErr != nil { return types.NewWrappedError(errorMessage, goTransitionErr) } diff --git a/client/client_test.go b/client/client_test.go index adf5c75..ad4fead 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -63,7 +63,7 @@ func stateCallback( data interface{}, state *Client, ) { - if newState == STATE_OAUTH_STARTED { + if newState == StateOAuthStarted { url, ok := data.(string) if !ok { @@ -73,7 +73,7 @@ func stateCallback( } } -func Test_server(t *testing.T) { +func TestServer(t *testing.T) { serverURI := getServerURI(t) state := &Client{} @@ -101,7 +101,7 @@ func Test_server(t *testing.T) { } } -func test_connect_oauth_parameter( +func testConnectOAuthParameter( t *testing.T, parameters httpw.URLParameters, expectedErr interface{}, @@ -115,7 +115,7 @@ func test_connect_oauth_parameter( configDirectory, "en", func(oldState FSMStateID, newState FSMStateID, data interface{}) bool { - if newState == STATE_OAUTH_STARTED { + if newState == StateOAuthStarted { server, serverErr := state.Servers.GetCustomServer(serverURI) if serverErr != nil { t.Fatalf("No server with error: %v", serverErr) @@ -168,7 +168,7 @@ func test_connect_oauth_parameter( } } -func Test_connect_oauth_parameters(t *testing.T) { +func TestConnectOAuthParameters(t *testing.T) { var ( failedCallbackParameterError *oauth.OAuthCallbackParameterError failedCallbackStateMatchError *oauth.OAuthCallbackStateMatchError @@ -194,11 +194,11 @@ func Test_connect_oauth_parameters(t *testing.T) { } for _, test := range tests { - test_connect_oauth_parameter(t, test.parameters, test.expectedErr) + testConnectOAuthParameter(t, test.parameters, test.expectedErr) } } -func Test_token_expired(t *testing.T) { +func TestTokenExpired(t *testing.T) { serverURI := getServerURI(t) expiredTTL := os.Getenv("OAUTH_EXPIRED_TTL") if expiredTTL == "" { @@ -274,7 +274,7 @@ func Test_token_expired(t *testing.T) { } } -func Test_token_invalid(t *testing.T) { +func TestTokenInvalid(t *testing.T) { serverURI := getServerURI(t) state := &Client{} @@ -303,7 +303,7 @@ func Test_token_invalid(t *testing.T) { t.Fatalf("Connect error before invalid: %v", configErr) } - dummy_value := "37" + dummyValue := "37" currentServer, serverErr := state.Servers.GetCurrentServer() if serverErr != nil { @@ -313,8 +313,8 @@ func Test_token_invalid(t *testing.T) { oauth := currentServer.GetOAuth() // Override tokens with invalid values - oauth.Token.Access = dummy_value - oauth.Token.Refresh = dummy_value + oauth.Token.Access = dummyValue + oauth.Token.Refresh = dummyValue _, _, configErr = state.GetConfigCustomServer(serverURI, false) @@ -322,17 +322,17 @@ func Test_token_invalid(t *testing.T) { t.Fatalf("Connect error after invalid: %v", configErr) } - if oauth.Token.Access == dummy_value { - t.Errorf("Access token is equal to dummy value: %s", dummy_value) + if oauth.Token.Access == dummyValue { + t.Errorf("Access token is equal to dummy value: %s", dummyValue) } - if oauth.Token.Refresh == dummy_value { - t.Errorf("Refresh token is equal to dummy value: %s", dummy_value) + if oauth.Token.Refresh == dummyValue { + t.Errorf("Refresh token is equal to dummy value: %s", dummyValue) } } // Test if an invalid profile will be corrected -func Test_invalid_profile_corrected(t *testing.T) { +func TestInvalidProfileCorrected(t *testing.T) { serverURI := getServerURI(t) state := &Client{} @@ -390,7 +390,7 @@ func Test_invalid_profile_corrected(t *testing.T) { } // Test if prefer tcp is handled correctly by checking the returned config and config type -func Test_prefer_tcp(t *testing.T) { +func TestPreferTCP(t *testing.T) { serverURI := getServerURI(t) state := &Client{} diff --git a/client/fsm.go b/client/fsm.go index bfe9c63..2ce60ba 100644 --- a/client/fsm.go +++ b/client/fsm.go @@ -17,78 +17,78 @@ type ( ) const ( - // Deregistered means the app is not registered with the wrapper - STATE_DEREGISTERED FSMStateID = iota + // StateDeregistered means the app is not registered with the wrapper + StateDeregistered FSMStateID = iota - // No Server means the user has not chosen a server yet - STATE_NO_SERVER + // StateNoServer means the user has not chosen a server yet + StateNoServer - // The user selected a Secure Internet server but needs to choose a location - STATE_ASK_LOCATION + // StateAskLocation means the user selected a Secure Internet server but needs to choose a location + StateAskLocation - // The user is currently selecting a server in the UI - STATE_SEARCH_SERVER + // StateSearchServer means the user is currently selecting a server in the UI + StateSearchServer - // We are loading the server details - STATE_LOADING_SERVER + // StateLoadingServer means we are loading the server details + StateLoadingServer - // Chosen Server means the user has chosen a server to connect to - STATE_CHOSEN_SERVER + // StateChosenServer means the user has chosen a server to connect to + StateChosenServer - // OAuth Started means the OAuth process has started - STATE_OAUTH_STARTED + // StateOAuthStarted means the OAuth process has started + StateOAuthStarted - // Authorized means the OAuth process has finished and the user is now authorized with the server - STATE_AUTHORIZED + // StateAuthorized means the OAuth process has finished and the user is now authorized with the server + StateAuthorized - // Requested config means the user has requested a config for connecting - STATE_REQUEST_CONFIG + // StateRequestConfig means the user has requested a config for connecting + StateRequestConfig - // Ask profile means the go code is asking for a profile selection from the UI - STATE_ASK_PROFILE + // StateAskProfile means the go code is asking for a profile selection from the UI + StateAskProfile - // Disconnected means the user has gotten a config for a server but is not connected yet - STATE_DISCONNECTED + // StateDisconnected means the user has gotten a config for a server but is not connected yet + StateDisconnected - // Disconnecting means the OS is disconnecting and the Go code is doing the /disconnect - STATE_DISCONNECTING + // StateDisconnecting means the OS is disconnecting and the Go code is doing the /disconnect + StateDisconnecting - // Connecting means the OS is establishing a connection to the server - STATE_CONNECTING + // StateConnecting means the OS is establishing a connection to the server + StateConnecting - // Connected means the user has been connected to the server - STATE_CONNECTED + // StateConnected means the user has been connected to the server + StateConnected ) func GetStateName(s FSMStateID) string { switch s { - case STATE_DEREGISTERED: + case StateDeregistered: return "Deregistered" - case STATE_NO_SERVER: + case StateNoServer: return "No_Server" - case STATE_ASK_LOCATION: + case StateAskLocation: return "Ask_Location" - case STATE_SEARCH_SERVER: + case StateSearchServer: return "Search_Server" - case STATE_LOADING_SERVER: + case StateLoadingServer: return "Loading_Server" - case STATE_CHOSEN_SERVER: + case StateChosenServer: return "Chosen_Server" - case STATE_OAUTH_STARTED: + case StateOAuthStarted: return "OAuth_Started" - case STATE_DISCONNECTED: + case StateDisconnected: return "Disconnected" - case STATE_REQUEST_CONFIG: + case StateRequestConfig: return "Request_Config" - case STATE_ASK_PROFILE: + case StateAskProfile: return "Ask_Profile" - case STATE_AUTHORIZED: + case StateAuthorized: return "Authorized" - case STATE_DISCONNECTING: + case StateDisconnecting: return "Disconnecting" - case STATE_CONNECTING: + case StateConnecting: return "Connecting" - case STATE_CONNECTED: + case StateConnected: return "Connected" default: panic("unknown conversion of state to string") @@ -101,107 +101,107 @@ func newFSM( debug bool, ) fsm.FSM { states := FSMStates{ - STATE_DEREGISTERED: FSMState{ - Transitions: []FSMTransition{{To: STATE_NO_SERVER, Description: "Client registers"}}, + StateDeregistered: FSMState{ + Transitions: []FSMTransition{{To: StateNoServer, Description: "Client registers"}}, }, - STATE_NO_SERVER: FSMState{ + StateNoServer: FSMState{ Transitions: []FSMTransition{ - {To: STATE_NO_SERVER, Description: "Reload list"}, - {To: STATE_LOADING_SERVER, Description: "User clicks a server in the UI"}, - {To: STATE_CHOSEN_SERVER, Description: "The server has been chosen"}, - {To: STATE_SEARCH_SERVER, Description: "The user is trying to choose a new server in the UI"}, - {To: STATE_CONNECTED, Description: "The user is already connected"}, - {To: STATE_ASK_LOCATION, Description: "Change the location in the main screen"}, + {To: StateNoServer, Description: "Reload list"}, + {To: StateLoadingServer, Description: "User clicks a server in the UI"}, + {To: StateChosenServer, Description: "The server has been chosen"}, + {To: StateSearchServer, Description: "The user is trying to choose a new server in the UI"}, + {To: StateConnected, Description: "The user is already connected"}, + {To: StateAskLocation, Description: "Change the location in the main screen"}, }, }, - STATE_SEARCH_SERVER: FSMState{ + StateSearchServer: FSMState{ Transitions: []FSMTransition{ - {To: STATE_LOADING_SERVER, Description: "User clicks a server in the UI"}, - {To: STATE_NO_SERVER, Description: "Cancel or Error"}, + {To: StateLoadingServer, Description: "User clicks a server in the UI"}, + {To: StateNoServer, Description: "Cancel or Error"}, }, - BackState: STATE_NO_SERVER, + BackState: StateNoServer, }, - STATE_ASK_LOCATION: FSMState{ + StateAskLocation: FSMState{ Transitions: []FSMTransition{ - {To: STATE_CHOSEN_SERVER, Description: "Location chosen"}, - {To: STATE_NO_SERVER, Description: "Go back or Error"}, - {To: STATE_SEARCH_SERVER, Description: "Cancel or Error"}, + {To: StateChosenServer, Description: "Location chosen"}, + {To: StateNoServer, Description: "Go back or Error"}, + {To: StateSearchServer, Description: "Cancel or Error"}, }, }, - STATE_LOADING_SERVER: FSMState{ + StateLoadingServer: FSMState{ Transitions: []FSMTransition{ - {To: STATE_CHOSEN_SERVER, Description: "Server info loaded"}, + {To: StateChosenServer, Description: "Server info loaded"}, { - To: STATE_ASK_LOCATION, + To: StateAskLocation, Description: "User chooses a Secure Internet server but no location is configured", }, - {To: STATE_NO_SERVER, Description: "Go back or Error"}, + {To: StateNoServer, Description: "Go back or Error"}, }, - BackState: STATE_NO_SERVER, + BackState: StateNoServer, }, - STATE_CHOSEN_SERVER: FSMState{ + StateChosenServer: FSMState{ Transitions: []FSMTransition{ - {To: STATE_AUTHORIZED, Description: "Found tokens in config"}, - {To: STATE_OAUTH_STARTED, Description: "No tokens found in config"}, + {To: StateAuthorized, Description: "Found tokens in config"}, + {To: StateOAuthStarted, Description: "No tokens found in config"}, }, }, - STATE_OAUTH_STARTED: FSMState{ + StateOAuthStarted: FSMState{ Transitions: []FSMTransition{ - {To: STATE_AUTHORIZED, Description: "User authorizes with browser"}, - {To: STATE_NO_SERVER, Description: "Go back or Error"}, - {To: STATE_SEARCH_SERVER, Description: "Cancel or Error"}, + {To: StateAuthorized, Description: "User authorizes with browser"}, + {To: StateNoServer, Description: "Go back or Error"}, + {To: StateSearchServer, Description: "Cancel or Error"}, }, - BackState: STATE_NO_SERVER, + BackState: StateNoServer, }, - STATE_AUTHORIZED: FSMState{ + StateAuthorized: FSMState{ Transitions: []FSMTransition{ - {To: STATE_OAUTH_STARTED, Description: "Re-authorize with OAuth"}, - {To: STATE_REQUEST_CONFIG, Description: "Client requests a config"}, - {To: STATE_NO_SERVER, Description: "Client wants to go back to the main screen"}, + {To: StateOAuthStarted, Description: "Re-authorize with OAuth"}, + {To: StateRequestConfig, Description: "Client requests a config"}, + {To: StateNoServer, Description: "Client wants to go back to the main screen"}, }, }, - STATE_REQUEST_CONFIG: FSMState{ + StateRequestConfig: FSMState{ Transitions: []FSMTransition{ - {To: STATE_ASK_PROFILE, Description: "Multiple profiles found and no profile chosen"}, - {To: STATE_DISCONNECTED, Description: "Only one profile or profile already chosen"}, - {To: STATE_NO_SERVER, Description: "Cancel or Error"}, - {To: STATE_OAUTH_STARTED, Description: "Re-authorize"}, + {To: StateAskProfile, Description: "Multiple profiles found and no profile chosen"}, + {To: StateDisconnected, Description: "Only one profile or profile already chosen"}, + {To: StateNoServer, Description: "Cancel or Error"}, + {To: StateOAuthStarted, Description: "Re-authorize"}, }, }, - STATE_ASK_PROFILE: FSMState{ + StateAskProfile: FSMState{ Transitions: []FSMTransition{ - {To: STATE_DISCONNECTED, Description: "User chooses profile"}, - {To: STATE_NO_SERVER, Description: "Cancel or Error"}, - {To: STATE_SEARCH_SERVER, Description: "Cancel or Error"}, + {To: StateDisconnected, Description: "User chooses profile"}, + {To: StateNoServer, Description: "Cancel or Error"}, + {To: StateSearchServer, Description: "Cancel or Error"}, }, }, - STATE_DISCONNECTED: FSMState{ + StateDisconnected: FSMState{ Transitions: []FSMTransition{ - {To: STATE_CONNECTING, Description: "OS reports it is trying to connect"}, - {To: STATE_REQUEST_CONFIG, Description: "User reconnects"}, - {To: STATE_NO_SERVER, Description: "User wants to choose a new server"}, - {To: STATE_OAUTH_STARTED, Description: "Re-authorize with OAuth"}, + {To: StateConnecting, Description: "OS reports it is trying to connect"}, + {To: StateRequestConfig, Description: "User reconnects"}, + {To: StateNoServer, Description: "User wants to choose a new server"}, + {To: StateOAuthStarted, Description: "Re-authorize with OAuth"}, }, - BackState: STATE_NO_SERVER, + BackState: StateNoServer, }, - STATE_DISCONNECTING: FSMState{ + StateDisconnecting: FSMState{ Transitions: []FSMTransition{ - {To: STATE_DISCONNECTED, Description: "Cancel or Error"}, - {To: STATE_DISCONNECTED, Description: "Done disconnecting"}, + {To: StateDisconnected, Description: "Cancel or Error"}, + {To: StateDisconnected, Description: "Done disconnecting"}, }, }, - STATE_CONNECTING: FSMState{ + StateConnecting: FSMState{ Transitions: []FSMTransition{ - {To: STATE_DISCONNECTED, Description: "Cancel or Error"}, - {To: STATE_CONNECTED, Description: "Done connecting"}, + {To: StateDisconnected, Description: "Cancel or Error"}, + {To: StateConnected, Description: "Done connecting"}, }, }, - STATE_CONNECTED: FSMState{ - Transitions: []FSMTransition{{To: STATE_DISCONNECTING, Description: "App wants to disconnect"}}, + StateConnected: FSMState{ + Transitions: []FSMTransition{{To: StateDisconnecting, Description: "App wants to disconnect"}}, }, } returnedFSM := fsm.FSM{} - returnedFSM.Init(STATE_DEREGISTERED, states, callback, directory, GetStateName, debug) + returnedFSM.Init(StateDeregistered, states, callback, directory, GetStateName, debug) return returnedFSM } @@ -253,17 +253,17 @@ func (e FSMWrongStateError) CustomError() *types.WrappedErrorMessage { // This indicates that the user wants to search for a new server. // Returns an error if this state transition is not possible. func (client *Client) SetSearchServer() error { - if !client.FSM.HasTransition(STATE_SEARCH_SERVER) { + if !client.FSM.HasTransition(StateSearchServer) { return client.handleError( "failed to set search server", FSMWrongStateTransitionError{ Got: client.FSM.Current, - Want: STATE_SEARCH_SERVER, + Want: StateSearchServer, }.CustomError(), ) } - client.FSM.GoTransition(STATE_SEARCH_SERVER) + client.FSM.GoTransition(StateSearchServer) return nil } @@ -272,17 +272,17 @@ func (client *Client) SetSearchServer() error { // Returns an error if this state transition is not possible. func (client *Client) SetConnected() error { errorMessage := "failed to set connected" - if client.InFSMState(STATE_CONNECTED) { + if client.InFSMState(StateConnected) { // already connected, show no error client.Logger.Warning("Already connected") return nil } - if !client.FSM.HasTransition(STATE_CONNECTED) { + if !client.FSM.HasTransition(StateConnected) { return client.handleError( errorMessage, FSMWrongStateTransitionError{ Got: client.FSM.Current, - Want: STATE_CONNECTED, + Want: StateConnected, }.CustomError(), ) } @@ -292,7 +292,7 @@ func (client *Client) SetConnected() error { return client.handleError(errorMessage, currentServerErr) } - client.FSM.GoTransitionWithData(STATE_CONNECTED, currentServer) + client.FSM.GoTransitionWithData(StateConnected, currentServer) return nil } @@ -301,17 +301,17 @@ func (client *Client) SetConnected() error { // Returns an error if this state transition is not possible. func (client *Client) SetConnecting() error { errorMessage := "failed to set connecting" - if client.InFSMState(STATE_CONNECTING) { + if client.InFSMState(StateConnecting) { // already loading connection, show no error client.Logger.Warning("Already connecting") return nil } - if !client.FSM.HasTransition(STATE_CONNECTING) { + if !client.FSM.HasTransition(StateConnecting) { return client.handleError( errorMessage, FSMWrongStateTransitionError{ Got: client.FSM.Current, - Want: STATE_CONNECTING, + Want: StateConnecting, }.CustomError(), ) } @@ -321,7 +321,7 @@ func (client *Client) SetConnecting() error { return client.handleError(errorMessage, currentServerErr) } - client.FSM.GoTransitionWithData(STATE_CONNECTING, currentServer) + client.FSM.GoTransitionWithData(StateConnecting, currentServer) return nil } @@ -330,17 +330,17 @@ func (client *Client) SetConnecting() error { // Returns an error if this state transition is not possible. func (client *Client) SetDisconnecting() error { errorMessage := "failed to set disconnecting" - if client.InFSMState(STATE_DISCONNECTING) { + if client.InFSMState(StateDisconnecting) { // already disconnecting, show no error client.Logger.Warning("Already disconnecting") return nil } - if !client.FSM.HasTransition(STATE_DISCONNECTING) { + if !client.FSM.HasTransition(StateDisconnecting) { return client.handleError( errorMessage, FSMWrongStateTransitionError{ Got: client.FSM.Current, - Want: STATE_DISCONNECTING, + Want: StateDisconnecting, }.CustomError(), ) } @@ -350,7 +350,7 @@ func (client *Client) SetDisconnecting() error { return client.handleError(errorMessage, currentServerErr) } - client.FSM.GoTransitionWithData(STATE_DISCONNECTING, currentServer) + client.FSM.GoTransitionWithData(StateDisconnecting, currentServer) return nil } @@ -360,17 +360,17 @@ func (client *Client) SetDisconnecting() error { // Returns an error if this state transition is not possible. func (client *Client) SetDisconnected(cleanup bool) error { errorMessage := "failed to set disconnected" - if client.InFSMState(STATE_DISCONNECTED) { + if client.InFSMState(StateDisconnected) { // already disconnected, show no error client.Logger.Warning("Already disconnected") return nil } - if !client.FSM.HasTransition(STATE_DISCONNECTED) { + if !client.FSM.HasTransition(StateDisconnected) { return client.handleError( errorMessage, FSMWrongStateTransitionError{ Got: client.FSM.Current, - Want: STATE_DISCONNECTED, + Want: StateDisconnected, }.CustomError(), ) } @@ -385,7 +385,7 @@ func (client *Client) SetDisconnected(cleanup bool) error { server.Disconnect(currentServer) } - client.FSM.GoTransitionWithData(STATE_DISCONNECTED, currentServer) + client.FSM.GoTransitionWithData(StateDisconnected, currentServer) return nil } @@ -406,7 +406,7 @@ func (client *Client) goBackInternal() { // GoBack transitions the FSM back to the previous UI state, for now this is always the NO_SERVER state. func (client *Client) GoBack() error { errorMessage := "failed to go back" - if client.InFSMState(STATE_DEREGISTERED) { + if client.InFSMState(StateDeregistered) { return client.handleError( errorMessage, FSMDeregisteredError{}.CustomError(), @@ -414,7 +414,7 @@ func (client *Client) GoBack() error { } // FIXME: Abitrary back transitions don't work because we need the approriate data - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) return nil } @@ -423,12 +423,12 @@ func (client *Client) GoBack() error { // An error is also returned if OAuth is in progress but it fails to cancel it. func (client *Client) CancelOAuth() error { errorMessage := "failed to cancel OAuth" - if !client.InFSMState(STATE_OAUTH_STARTED) { + if !client.InFSMState(StateOAuthStarted) { return client.handleError( errorMessage, FSMWrongStateError{ Got: client.FSM.Current, - Want: STATE_OAUTH_STARTED, + Want: StateOAuthStarted, }.CustomError(), ) } diff --git a/client/server.go b/client/server.go index d22dc65..12e5932 100644 --- a/client/server.go +++ b/client/server.go @@ -20,7 +20,7 @@ func (client *Client) getConfigAuth( if loginErr != nil { return "", "", loginErr } - client.FSM.GoTransition(STATE_REQUEST_CONFIG) + client.FSM.GoTransition(StateRequestConfig) validProfile, profileErr := server.HasValidProfile(chosenServer, client.SupportsWireguard) if profileErr != nil { @@ -72,7 +72,7 @@ func (client *Client) getConfig( preferTCP bool, ) (string, string, error) { errorMessage := "failed to get a configuration for OpenVPN/Wireguard" - if client.InFSMState(STATE_DEREGISTERED) { + if client.InFSMState(StateDeregistered) { return "", "", types.NewWrappedError( errorMessage, FSMDeregisteredError{}.CustomError(), @@ -97,7 +97,7 @@ func (client *Client) getConfig( } // Signal the server display info - client.FSM.GoTransitionWithData(STATE_DISCONNECTED, currentServer) + client.FSM.GoTransitionWithData(StateDisconnected, currentServer) // Save the config saveErr := client.Config.Save(&client) @@ -139,7 +139,7 @@ func (client *Client) SetSecureLocation(countryCode string) error { // It returns an error if the server cannot be removed due to the state being DEREGISTERED. // Note that if the server does not exist, it returns nil as an error. func (client *Client) RemoveSecureInternet() error { - if client.InFSMState(STATE_DEREGISTERED) { + if client.InFSMState(StateDeregistered) { return client.handleError( "failed to remove Secure Internet", FSMDeregisteredError{}.CustomError(), @@ -147,7 +147,7 @@ func (client *Client) RemoveSecureInternet() error { } // No error because we can only have one secure internet server and if there are no secure internet servers, this is a NO-OP client.Servers.RemoveSecureInternet() - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) // Save the config saveErr := client.Config.Save(&client) if saveErr != nil { @@ -163,7 +163,7 @@ func (client *Client) RemoveSecureInternet() error { // It returns an error if the server cannot be removed due to the state being DEREGISTERED. // Note that if the server does not exist, it returns nil as an error. func (client *Client) RemoveInstituteAccess(url string) error { - if client.InFSMState(STATE_DEREGISTERED) { + if client.InFSMState(StateDeregistered) { return client.handleError( "failed to remove Institute Access", FSMDeregisteredError{}.CustomError(), @@ -171,7 +171,7 @@ func (client *Client) RemoveInstituteAccess(url string) error { } // No error because this is a NO-OP if the server doesn't exist client.Servers.RemoveInstituteAccess(url) - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) // Save the config saveErr := client.Config.Save(&client) if saveErr != nil { @@ -187,7 +187,7 @@ func (client *Client) RemoveInstituteAccess(url string) error { // It returns an error if the server cannot be removed due to the state being DEREGISTERED. // Note that if the server does not exist, it returns nil as an error. func (client *Client) RemoveCustomServer(url string) error { - if client.InFSMState(STATE_DEREGISTERED) { + if client.InFSMState(StateDeregistered) { return client.handleError( "failed to remove Custom Server", FSMDeregisteredError{}.CustomError(), @@ -195,7 +195,7 @@ func (client *Client) RemoveCustomServer(url string) error { } // No error because this is a NO-OP if the server doesn't exist client.Servers.RemoveCustomServer(url) - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) // Save the config saveErr := client.Config.Save(&client) if saveErr != nil { @@ -217,7 +217,7 @@ func (client *Client) AddInstituteServer(url string) (server.Server, error) { } // Indicate that we're loading the server - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) // FIXME: Do nothing with discovery here as the client already has it // So pass a server as the parameter @@ -242,7 +242,7 @@ func (client *Client) AddInstituteServer(url string) (server.Server, error) { } // Indicate that we want to authorize this server - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) // Authorize it loginErr := client.ensureLogin(server) @@ -252,7 +252,7 @@ func (client *Client) AddInstituteServer(url string) (server.Server, error) { return nil, client.handleError(errorMessage, loginErr) } - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) return server, nil } @@ -270,7 +270,7 @@ func (client *Client) AddSecureInternetHomeServer(orgID string) (server.Server, } // Indicate that we're loading the server - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) // Get the secure internet URL from discovery secureOrg, secureServer, discoErr := client.Discovery.GetSecureHomeArgs(orgID) @@ -302,7 +302,7 @@ func (client *Client) AddSecureInternetHomeServer(orgID string) (server.Server, } // Server has been chosen for authentication - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) // Authorize it loginErr := client.ensureLogin(server) @@ -311,7 +311,7 @@ func (client *Client) AddSecureInternetHomeServer(orgID string) (server.Server, _ = client.RemoveSecureInternet() return nil, client.handleError(errorMessage, loginErr) } - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) return server, nil } @@ -325,7 +325,7 @@ func (client *Client) AddCustomServer(url string) (server.Server, error) { } // Indicate that we're loading the server - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) customServer := &types.DiscoveryServer{ BaseURL: url, @@ -348,7 +348,7 @@ func (client *Client) AddCustomServer(url string) (server.Server, error) { } // Server has been chosen for authentication - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) // Authorize it loginErr := client.ensureLogin(server) @@ -358,7 +358,7 @@ func (client *Client) AddCustomServer(url string) (server.Server, error) { return nil, client.handleError(errorMessage, loginErr) } - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) return server, nil } @@ -373,7 +373,7 @@ func (client *Client) GetConfigInstituteAccess(url string, preferTCP bool) (stri return "", "", client.handleError(errorMessage, LetsConnectNotSupportedError{}) } - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) // Get the server if it exists server, serverErr := client.Servers.GetInstituteAccess(url) @@ -389,7 +389,7 @@ func (client *Client) GetConfigInstituteAccess(url string, preferTCP bool) (stri } // The server has now been chosen - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) config, configType, configErr := client.getConfig(server, preferTCP) if configErr != nil { @@ -416,7 +416,7 @@ func (client *Client) GetConfigSecureInternet( return "", "", client.handleError(errorMessage, LetsConnectNotSupportedError{}) } - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) // Get the server if it exists server, serverErr := client.Servers.GetSecureInternetHomeServer() @@ -431,7 +431,7 @@ func (client *Client) GetConfigSecureInternet( return "", "", client.handleError(errorMessage, currentErr) } - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) config, configType, configErr := client.getConfig(server, preferTCP) if configErr != nil { @@ -452,7 +452,7 @@ func (client *Client) GetConfigCustomServer(url string, preferTCP bool) (string, return "", "", client.handleError(errorMessage, urlErr) } - client.FSM.GoTransition(STATE_LOADING_SERVER) + client.FSM.GoTransition(StateLoadingServer) // Get the server if it exists server, serverErr := client.Servers.GetCustomServer(url) @@ -467,7 +467,7 @@ func (client *Client) GetConfigCustomServer(url string, preferTCP bool) (string, return "", "", client.handleError(errorMessage, currentErr) } - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + client.FSM.GoTransition(StateChosenServer) config, configType, configErr := client.getConfig(server, preferTCP) if configErr != nil { @@ -483,13 +483,13 @@ func (client *Client) askSecureLocation() error { locations := client.Discovery.GetSecureLocationList() // Ask for the location in the callback - goTransitionErr := client.FSM.GoTransitionRequired(STATE_ASK_LOCATION, locations) + goTransitionErr := client.FSM.GoTransitionRequired(StateAskLocation, locations) if goTransitionErr != nil { return types.NewWrappedError(errorMessage, goTransitionErr) } // The state has changed, meaning setting the secure location was not successful - if client.FSM.Current != STATE_ASK_LOCATION { + if client.FSM.Current != StateAskLocation { // TODO: maybe a custom type for this errors.new? return types.NewWrappedError( errorMessage, @@ -505,12 +505,12 @@ func (client *Client) askSecureLocation() error { func (client *Client) ChangeSecureLocation() error { errorMessage := "failed to change location from the main screen" - if !client.InFSMState(STATE_NO_SERVER) { + if !client.InFSMState(StateNoServer) { return client.handleError( errorMessage, FSMWrongStateError{ Got: client.FSM.Current, - Want: STATE_NO_SERVER, + Want: StateNoServer, }.CustomError(), ) } @@ -521,7 +521,7 @@ func (client *Client) ChangeSecureLocation() error { } // Go back to the main screen - client.FSM.GoTransitionWithData(STATE_NO_SERVER, client.Servers) + client.FSM.GoTransitionWithData(StateNoServer, client.Servers) return nil } @@ -538,8 +538,8 @@ func (client *Client) RenewSession() error { } // The server has not been chosen yet, this means that we want to manually renew - if client.FSM.InState(STATE_NO_SERVER) { - client.FSM.GoTransition(STATE_CHOSEN_SERVER) + if client.FSM.InState(StateNoServer) { + client.FSM.GoTransition(StateChosenServer) } server.MarkTokensForRenew(currentServer) @@ -555,9 +555,9 @@ func (client *Client) RenewSession() error { // If there is no server then this returns false and logs with INFO if so // In other cases it simply checks the expiry time and calculates according to: https://github.com/eduvpn/documentation/blob/b93854dcdd22050d5f23e401619e0165cb8bc591/API.md#session-expiry. func (client *Client) ShouldRenewButton() bool { - if !client.InFSMState(STATE_CONNECTED) && !client.InFSMState(STATE_CONNECTING) && - !client.InFSMState(STATE_DISCONNECTED) && - !client.InFSMState(STATE_DISCONNECTING) { + if !client.InFSMState(StateConnected) && !client.InFSMState(StateConnecting) && + !client.InFSMState(StateDisconnected) && + !client.InFSMState(StateDisconnecting) { return false } @@ -583,7 +583,7 @@ func (client *Client) ensureLogin(chosenServer server.Server) error { if server.NeedsRelogin(chosenServer) { url, urlErr := server.GetOAuthURL(chosenServer, client.Name) - goTransitionErr := client.FSM.GoTransitionRequired(STATE_OAUTH_STARTED, url) + goTransitionErr := client.FSM.GoTransitionRequired(StateOAuthStarted, url) if goTransitionErr != nil { return types.NewWrappedError(errorMessage, goTransitionErr) } @@ -601,7 +601,7 @@ func (client *Client) ensureLogin(chosenServer server.Server) error { } } // OAuth was valid, ensure we are in the authorized state - client.FSM.GoTransition(STATE_AUTHORIZED) + client.FSM.GoTransition(StateAuthorized) return nil } diff --git a/cmd/cli/main.go b/cmd/cli/main.go index 96ca42f..ec78754 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -82,11 +82,11 @@ func stateCallback( newState client.FSMStateID, data interface{}, ) { - if newState == client.STATE_OAUTH_STARTED { + if newState == client.StateOAuthStarted { openBrowser(data) } - if newState == client.STATE_ASK_PROFILE { + if newState == client.StateAskProfile { sendProfile(state, data) } } @@ -153,17 +153,17 @@ func printConfig(url string, serverType ServerTypes) { // The main function // It parses the arguments and executes the correct functions func main() { - customUrlArg := flag.String("get-custom", "", "The url of a custom server to connect to") + customURLArg := flag.String("get-custom", "", "The url of a custom server to connect to") urlArg := flag.String("get-institute", "", "The url of an institute to connect to") secureInternet := flag.String("get-secure", "", "Gets secure internet servers") flag.Parse() // Connect to a VPN by getting an Institute Access config - customUrlString := *customUrlArg + customURLString := *customURLArg urlString := *urlArg secureInternetString := *secureInternet - if customUrlString != "" { - printConfig(customUrlString, ServerTypeCustom) + if customURLString != "" { + printConfig(customURLString, ServerTypeCustom) return } else if urlString != "" { printConfig(urlString, ServerTypeInstituteAccess) diff --git a/exports/disco.go b/exports/disco.go index 6db0e86..c5e544a 100644 --- a/exports/disco.go +++ b/exports/disco.go @@ -54,7 +54,7 @@ func getCPtrDiscoOrganization( C.malloc(C.size_t(unsafe.Sizeof(C.discoveryOrganization{}))), ) returnedStruct.display_name = C.CString(state.GetTranslated(organization.DisplayName)) - returnedStruct.org_id = C.CString(organization.OrgId) + returnedStruct.org_id = C.CString(organization.OrgID) returnedStruct.secure_internet_home = C.CString(organization.SecureInternetHome) returnedStruct.keyword_list = C.CString(state.GetTranslated(organization.KeywordList)) return returnedStruct diff --git a/exports/exports.go b/exports/exports.go index 8e418d4..fb972fc 100644 --- a/exports/exports.go +++ b/exports/exports.go @@ -21,7 +21,7 @@ import ( "github.com/eduvpn/eduvpn-common/types" ) -var P_StateCallbacks map[string]C.PythonCB +var PStateCallbacks map[string]C.PythonCB var VPNStates map[string]*client.Client @@ -31,23 +31,23 @@ func GetStateData( data interface{}, ) unsafe.Pointer { switch stateID { - case client.STATE_NO_SERVER: + case client.StateNoServer: return (unsafe.Pointer)(getTransitionDataServers(state, data)) - case client.STATE_OAUTH_STARTED: + case client.StateOAuthStarted: if converted, ok := data.(string); ok { return (unsafe.Pointer)(C.CString(converted)) } - case client.STATE_ASK_LOCATION: + case client.StateAskLocation: return (unsafe.Pointer)(getTransitionSecureLocations(data)) - case client.STATE_ASK_PROFILE: + case client.StateAskProfile: return (unsafe.Pointer)(getTransitionProfiles(data)) - case client.STATE_DISCONNECTED: + case client.StateDisconnected: return (unsafe.Pointer)(getTransitionServer(state, data)) - case client.STATE_DISCONNECTING: + case client.StateDisconnecting: return (unsafe.Pointer)(getTransitionServer(state, data)) - case client.STATE_CONNECTING: + case client.StateConnecting: return (unsafe.Pointer)(getTransitionServer(state, data)) - case client.STATE_CONNECTED: + case client.StateConnected: return (unsafe.Pointer)(getTransitionServer(state, data)) default: return nil @@ -58,20 +58,20 @@ func GetStateData( func StateCallback( state *client.Client, name string, - old_state client.FSMStateID, - new_state client.FSMStateID, + oldState client.FSMStateID, + newState client.FSMStateID, data interface{}, ) bool { - P_StateCallback, exists := P_StateCallbacks[name] - if !exists || P_StateCallback == nil { + PStateCallback, exists := PStateCallbacks[name] + if !exists || PStateCallback == nil { return false } - name_c := C.CString(name) - oldState_c := C.int(old_state) - newState_c := C.int(new_state) - data_c := GetStateData(state, new_state, data) - handled := C.call_callback(P_StateCallback, name_c, oldState_c, newState_c, data_c) - C.free(unsafe.Pointer(name_c)) + nameC := C.CString(name) + oldStateC := C.int(oldState) + newStateC := C.int(newState) + dataC := GetStateData(state, newState, data) + handled := C.call_callback(PStateCallback, nameC, oldStateC, newStateC, dataC) + C.free(unsafe.Pointer(nameC)) // data_c gets freed by the wrapper return handled == C.int(1) } @@ -80,7 +80,7 @@ func GetVPNState(name string) (*client.Client, error) { state, exists := VPNStates[name] if !exists || state == nil { - return nil, fmt.Errorf("State with name %s not found", name) + return nil, fmt.Errorf("state with name %s not found", name) } return state, nil @@ -89,7 +89,7 @@ func GetVPNState(name string) (*client.Client, error) { //export Register func Register( name *C.char, - config_directory *C.char, + configDirectory *C.char, language *C.char, stateCallback C.PythonCB, debug C.int, @@ -102,14 +102,14 @@ func Register( if VPNStates == nil { VPNStates = make(map[string]*client.Client) } - if P_StateCallbacks == nil { - P_StateCallbacks = make(map[string]C.PythonCB) + if PStateCallbacks == nil { + PStateCallbacks = make(map[string]C.PythonCB) } VPNStates[nameStr] = state - P_StateCallbacks[nameStr] = stateCallback + PStateCallbacks[nameStr] = stateCallback registerErr := state.Register( nameStr, - C.GoString(config_directory), + C.GoString(configDirectory), C.GoString(language), func(old client.FSMStateID, new client.FSMStateID, data interface{}) bool { return StateCallback(state, nameStr, old, new, data) diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index 01978fe..b0b20fa 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -113,7 +113,7 @@ func (discovery *Discovery) GetServerByCountryCode( func (discovery *Discovery) getOrgByID(orgID string) (*types.DiscoveryOrganization, error) { for _, organization := range discovery.Organizations.List { - if organization.OrgId == orgID { + if organization.OrgID == orgID { return &organization, nil } } @@ -153,9 +153,9 @@ func (discovery *Discovery) DetermineServersUpdate() bool { return true } // 1 hour from the last update - should_update_time := discovery.Servers.Timestamp.Add(1 * time.Hour) + shouldUpdateTime := discovery.Servers.Timestamp.Add(1 * time.Hour) now := time.Now() - return !now.Before(should_update_time) + return !now.Before(shouldUpdateTime) } // Get the organization list diff --git a/internal/fsm/fsm.go b/internal/fsm/fsm.go index 1b45ce8..b51a5c9 100644 --- a/internal/fsm/fsm.go +++ b/internal/fsm/fsm.go @@ -75,8 +75,8 @@ func (fsm *FSM) InState(check FSMStateID) bool { } func (fsm *FSM) HasTransition(check FSMStateID) bool { - for _, transition_state := range fsm.States[fsm.Current].Transitions { - if transition_state.To == check { + for _, transitionState := range fsm.States[fsm.Current].Transitions { + if transitionState.To == check { return true } } @@ -143,12 +143,12 @@ func (fsm *FSM) GoTransition(newState FSMStateID) bool { func (fsm *FSM) generateMermaidGraph() string { graph := "graph TD\n" - sorted_fsm := make(FSMStateIDSlice, 0, len(fsm.States)) - for state_id := range fsm.States { - sorted_fsm = append(sorted_fsm, state_id) + sortedFSM := make(FSMStateIDSlice, 0, len(fsm.States)) + for stateID := range fsm.States { + sortedFSM = append(sortedFSM, stateID) } - sort.Sort(sorted_fsm) - for _, state := range sorted_fsm { + sort.Sort(sortedFSM) + for _, state := range sortedFSM { transitions := fsm.States[state].Transitions for _, transition := range transitions { if state == fsm.Current { diff --git a/internal/http/http.go b/internal/http/http.go index 005a665..a9d3ea2 100644 --- a/internal/http/http.go +++ b/internal/http/http.go @@ -170,13 +170,13 @@ func (e *HTTPStatusError) Error() string { ) } -type HTTPParseJsonError struct { +type HTTPParseJSONError struct { URL string Body string Err error } -func (e *HTTPParseJsonError) Error() string { +func (e *HTTPParseJSONError) Error() string { return fmt.Sprintf( "failed parsing json %s for HTTP resource: %s with error: %v", e.Body, diff --git a/internal/log/log.go b/internal/log/log.go index 8dc3ad0..2ab6549 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -20,32 +20,32 @@ type LogLevel int8 const ( // No level set, not allowed - LOG_NOTSET LogLevel = iota + LogNotSet LogLevel = iota // Log debug, this message is not an error but is there for debugging - LOG_DEBUG + LogDebug // Log info, this message is not an error but is there for additional information - LOG_INFO + LogInfo // Log only to provide a warning, the app still functions - LOG_WARNING + LogWarning // Log to provide a generic error, the app still functions but some functionality might not work - LOG_ERROR + LogError // Log to provide a fatal error, the app cannot function correctly when such an error occurs - LOG_FATAL + LogFatal ) func (e LogLevel) String() string { switch e { - case LOG_NOTSET: + case LogNotSet: return "NOTSET" - case LOG_DEBUG: + case LogDebug: return "DEBUG" - case LOG_INFO: + case LogInfo: return "INFO" - case LOG_WARNING: + case LogWarning: return "WARNING" - case LOG_ERROR: + case LogError: return "ERROR" - case LOG_FATAL: + case LogFatal: return "FATAL" default: return "UNKNOWN" @@ -79,35 +79,35 @@ func (logger *FileLogger) Inherit(label string, err error) { msg := fmt.Sprintf("%s with err: %s", label, types.GetErrorTraceback(err)) switch level { - case types.ERR_INFO: + case types.ErrInfo: logger.Info(msg) - case types.ERR_WARNING: + case types.ErrWarning: logger.Warning(msg) - case types.ERR_OTHER: + case types.ErrOther: logger.Error(msg) - case types.ERR_FATAL: + case types.ErrFatal: logger.Fatal(msg) } } func (logger *FileLogger) Debug(msg string, params ...interface{}) { - logger.log(LOG_DEBUG, msg, params...) + logger.log(LogDebug, msg, params...) } func (logger *FileLogger) Info(msg string, params ...interface{}) { - logger.log(LOG_INFO, msg, params...) + logger.log(LogInfo, msg, params...) } func (logger *FileLogger) Warning(msg string, params ...interface{}) { - logger.log(LOG_WARNING, msg, params...) + logger.log(LogWarning, msg, params...) } func (logger *FileLogger) Error(msg string, params ...interface{}) { - logger.log(LOG_ERROR, msg, params...) + logger.log(LogError, msg, params...) } func (logger *FileLogger) Fatal(msg string, params ...interface{}) { - logger.log(LOG_FATAL, msg, params...) + logger.log(LogFatal, msg, params...) } func (logger *FileLogger) Close() { @@ -119,9 +119,9 @@ func (logger *FileLogger) getFilename(directory string) string { } func (logger *FileLogger) log(level LogLevel, msg string, params ...interface{}) { - if level >= logger.Level && logger.Level != LOG_NOTSET { - formatted_msg := fmt.Sprintf(msg, params...) - format := fmt.Sprintf("- Go - %s - %s", level.String(), formatted_msg) + if level >= logger.Level && logger.Level != LogNotSet { + formattedMsg := fmt.Sprintf(msg, params...) + format := fmt.Sprintf("- Go - %s - %s", level.String(), formattedMsg) // To log file log.Println(format) } diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 9518d79..1f3b719 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -121,7 +121,7 @@ func (oauth *OAuth) setupListener() error { func (oauth *OAuth) getTokensWithCallback() error { errorMessage := "failed getting tokens with callback" if oauth.Session.Listener == nil { - return types.NewWrappedError(errorMessage, errors.New("No listener")) + return types.NewWrappedError(errorMessage, errors.New("no listener")) } mux := http.NewServeMux() // server /callback over the listener address @@ -161,7 +161,7 @@ func (oauth *OAuth) getTokensWithAuthCode(authCode string) error { "content-type": {"application/x-www-form-urlencoded"}, } opts := &httpw.HTTPOptionalParams{Headers: headers, Body: data} - current_time := time.Now() + currentTime := time.Now() _, body, bodyErr := httpw.HTTPPostWithOpts(reqURL, opts) if bodyErr != nil { return types.NewWrappedError(errorMessage, bodyErr) @@ -174,11 +174,11 @@ func (oauth *OAuth) getTokensWithAuthCode(authCode string) error { if jsonErr != nil { return types.NewWrappedError( errorMessage, - &httpw.HTTPParseJsonError{URL: reqURL, Body: string(body), Err: jsonErr}, + &httpw.HTTPParseJSONError{URL: reqURL, Body: string(body), Err: jsonErr}, ) } - tokenStructure.ExpiredTimestamp = current_time.Add( + tokenStructure.ExpiredTimestamp = currentTime.Add( time.Second * time.Duration(tokenStructure.Expires), ) oauth.Token = tokenStructure @@ -186,9 +186,9 @@ func (oauth *OAuth) getTokensWithAuthCode(authCode string) error { } func (oauth *OAuth) isTokensExpired() bool { - expired_time := oauth.Token.ExpiredTimestamp - current_time := time.Now() - return !current_time.Before(expired_time) + expiredTime := oauth.Token.ExpiredTimestamp + currentTime := time.Now() + return !currentTime.Before(expiredTime) } // Get the access and refresh tokens with a previously received refresh token @@ -205,7 +205,7 @@ func (oauth *OAuth) getTokensWithRefresh() error { "content-type": {"application/x-www-form-urlencoded"}, } opts := &httpw.HTTPOptionalParams{Headers: headers, Body: data} - current_time := time.Now() + currentTime := time.Now() _, body, bodyErr := httpw.HTTPPostWithOpts(reqURL, opts) if bodyErr != nil { return types.NewWrappedError(errorMessage, bodyErr) @@ -217,11 +217,11 @@ func (oauth *OAuth) getTokensWithRefresh() error { if jsonErr != nil { return types.NewWrappedError( errorMessage, - &httpw.HTTPParseJsonError{URL: reqURL, Body: string(body), Err: jsonErr}, + &httpw.HTTPParseJSONError{URL: reqURL, Body: string(body), Err: jsonErr}, ) } - tokenStructure.ExpiredTimestamp = current_time.Add( + tokenStructure.ExpiredTimestamp = currentTime.Add( time.Second * time.Duration(tokenStructure.Expires), ) oauth.Token = tokenStructure @@ -374,7 +374,7 @@ func (oauth OAuth) GetListenerPort() (int, error) { errorMessage := "failed to get listener port" if oauth.Session.Listener == nil { - return 0, types.NewWrappedError(errorMessage, errors.New("No OAuth listener")) + return 0, types.NewWrappedError(errorMessage, errors.New("no OAuth listener")) } return oauth.Session.Listener.Addr().(*net.TCPAddr).Port, nil } @@ -444,7 +444,7 @@ func (oauth *OAuth) Exchange() error { func (oauth *OAuth) Cancel() { oauth.Session.CallbackError = types.NewWrappedErrorLevel( - types.ERR_INFO, + types.ErrInfo, "cancelled OAuth", &OAuthCancelledCallbackError{}, ) diff --git a/internal/server/api.go b/internal/server/api.go index be7281c..d315ada 100644 --- a/internal/server/api.go +++ b/internal/server/api.go @@ -20,7 +20,9 @@ func APIGetEndpoints(baseURL string) (*ServerEndpoints, error) { return nil, types.NewWrappedError(errorMessage, urlErr) } - url.Path = path.Join(url.Path, WellKnownPath) + wellKnownPath := "/.well-known/vpn-user-portal" + + url.Path = path.Join(url.Path, wellKnownPath) _, body, bodyErr := httpw.HTTPGet(url.String()) if bodyErr != nil { @@ -140,7 +142,7 @@ func GetPreferTCPString(preferTCP bool) string { func APIConnectWireguard( server Server, - profile_id string, + profileID string, pubkey string, preferTCP bool, supportsOpenVPN bool, @@ -158,7 +160,7 @@ func APIConnectWireguard( } urlForm := url.Values{ - "profile_id": {profile_id}, + "profile_id": {profileID}, "public_key": {pubkey}, "prefer_tcp": {GetPreferTCPString(preferTCP)}, } @@ -191,7 +193,7 @@ func APIConnectWireguard( return string(connectBody), content, pTime, nil } -func APIConnectOpenVPN(server Server, profile_id string, preferTCP bool) (string, time.Time, error) { +func APIConnectOpenVPN(server Server, profileID string, preferTCP bool) (string, time.Time, error) { errorMessage := "failed obtaining an OpenVPN configuration" headers := http.Header{ "content-type": {"application/x-www-form-urlencoded"}, @@ -199,7 +201,7 @@ func APIConnectOpenVPN(server Server, profile_id string, preferTCP bool) (string } urlForm := url.Values{ - "profile_id": {profile_id}, + "profile_id": {profileID}, "prefer_tcp": {GetPreferTCPString(preferTCP)}, } diff --git a/internal/server/common.go b/internal/server/common.go index 6cd5dc2..8f4eabc 100644 --- a/internal/server/common.go +++ b/internal/server/common.go @@ -92,9 +92,6 @@ type ServerEndpoints struct { V string `json:"v"` } -// Make this a var which we can overwrite in the tests -var WellKnownPath string = "/.well-known/vpn-user-portal" - func (servers *Servers) GetCurrentServer() (Server, error) { errorMessage := "failed getting current server" if servers.IsType == SecureInternetServerType { @@ -372,7 +369,7 @@ func wireguardGetConfig(server Server, preferTCP bool, supportsOpenVPN bool) (st return "", "", types.NewWrappedError(errorMessage, baseErr) } - profile_id := base.Profiles.Current + profileID := base.Profiles.Current wireguardKey, wireguardErr := wireguard.GenerateKey() if wireguardErr != nil { @@ -382,7 +379,7 @@ func wireguardGetConfig(server Server, preferTCP bool, supportsOpenVPN bool) (st wireguardPublicKey := wireguardKey.PublicKey().String() config, content, expires, configErr := APIConnectWireguard( server, - profile_id, + profileID, wireguardPublicKey, preferTCP, supportsOpenVPN, @@ -414,8 +411,8 @@ func openVPNGetConfig(server Server, preferTCP bool) (string, string, error) { if baseErr != nil { return "", "", types.NewWrappedError(errorMessage, baseErr) } - profile_id := base.Profiles.Current - configOpenVPN, expires, configErr := APIConnectOpenVPN(server, profile_id, preferTCP) + profileID := base.Profiles.Current + configOpenVPN, expires, configErr := APIConnectOpenVPN(server, profileID, preferTCP) // Store start and end time base.StartTime = time.Now() @@ -515,7 +512,7 @@ func GetConfig(server Server, clientSupportsWireguard bool, preferTCP bool) (str config, configType, configErr = openVPNGetConfig(server, preferTCP) // The config supports no available protocol because the profile only supports WireGuard but the client doesn't } else { - return "", "", types.NewWrappedError(errorMessage, errors.New("No supported protocol found")) + return "", "", types.NewWrappedError(errorMessage, errors.New("no supported protocol found")) } if configErr != nil { diff --git a/internal/server/custom.go b/internal/server/custom.go index 6ba6503..8bde848 100644 --- a/internal/server/custom.go +++ b/internal/server/custom.go @@ -15,14 +15,14 @@ func (servers *Servers) SetCustomServer(server Server) error { } if base.Type != "custom_server" { - return types.NewWrappedError(errorMessage, errors.New("Not a custom server")) + return types.NewWrappedError(errorMessage, errors.New("not a custom server")) } if _, ok := servers.CustomServers.Map[base.URL]; ok { servers.CustomServers.CurrentURL = base.URL servers.IsType = CustomServerType } else { - return types.NewWrappedError(errorMessage, errors.New("Not a custom server")) + return types.NewWrappedError(errorMessage, errors.New("not a custom server")) } return nil } @@ -31,7 +31,7 @@ func (servers *Servers) GetCustomServer(url string) (*InstituteAccessServer, err if server, ok := servers.CustomServers.Map[url]; ok { return server, nil } - return nil, types.NewWrappedError("failed to get institute access server", fmt.Errorf("No custom server with URL: %s", url)) + return nil, types.NewWrappedError("failed to get institute access server", fmt.Errorf("no custom server with URL: %s", url)) } func (servers *Servers) RemoveCustomServer(url string) { diff --git a/internal/server/instituteaccess.go b/internal/server/instituteaccess.go index 045535a..33d8b52 100644 --- a/internal/server/instituteaccess.go +++ b/internal/server/instituteaccess.go @@ -30,14 +30,14 @@ func (servers *Servers) SetInstituteAccess(server Server) error { } if base.Type != "institute_access" { - return types.NewWrappedError(errorMessage, errors.New("Not an institute access server")) + return types.NewWrappedError(errorMessage, errors.New("not an institute access server")) } if _, ok := servers.InstituteServers.Map[base.URL]; ok { servers.InstituteServers.CurrentURL = base.URL servers.IsType = InstituteAccessServerType } else { - return types.NewWrappedError(errorMessage, errors.New("No such institute access server")) + return types.NewWrappedError(errorMessage, errors.New("no such institute access server")) } return nil } @@ -46,7 +46,7 @@ func (servers *Servers) GetInstituteAccess(url string) (*InstituteAccessServer, if server, ok := servers.InstituteServers.Map[url]; ok { return server, nil } - return nil, types.NewWrappedError("failed to get institute access server", fmt.Errorf("No institute access server with URL: %s", url)) + return nil, types.NewWrappedError("failed to get institute access server", fmt.Errorf("no institute access server with URL: %s", url)) } func (servers *Servers) RemoveInstituteAccess(url string) { diff --git a/internal/server/secureinternet.go b/internal/server/secureinternet.go index cfe9ea1..f0b308f 100644 --- a/internal/server/secureinternet.go +++ b/internal/server/secureinternet.go @@ -26,7 +26,7 @@ type SecureInternetHomeServer struct { func (servers *Servers) GetSecureInternetHomeServer() (*SecureInternetHomeServer, error) { if !servers.HasSecureLocation() { - return nil, errors.New("No secure internet home server") + return nil, errors.New("no secure internet home server") } return &servers.SecureInternetHomeServer, nil } @@ -39,7 +39,7 @@ func (servers *Servers) SetSecureInternet(server Server) error { } if base.Type != "secure_internet" { - return types.NewWrappedError(errorMessage, errors.New("Not a secure internet server")) + return types.NewWrappedError(errorMessage, errors.New("not a secure internet server")) } // The location should already be configured @@ -58,13 +58,13 @@ func (servers *Servers) RemoveSecureInternet() { } } -func (secure *SecureInternetHomeServer) GetOAuth() *oauth.OAuth { - return &secure.OAuth +func (server *SecureInternetHomeServer) GetOAuth() *oauth.OAuth { + return &server.OAuth } -func (secure *SecureInternetHomeServer) GetTemplateAuth() func(string) string { +func (server *SecureInternetHomeServer) GetTemplateAuth() func(string) string { return func(authURL string) string { - return util.ReplaceWAYF(secure.AuthorizationTemplate, authURL, secure.HomeOrganizationID) + return util.ReplaceWAYF(server.AuthorizationTemplate, authURL, server.HomeOrganizationID) } } @@ -92,23 +92,23 @@ func (servers *Servers) HasSecureLocation() bool { return servers.SecureInternetHomeServer.CurrentLocation != "" } -func (secure *SecureInternetHomeServer) addLocation( +func (server *SecureInternetHomeServer) addLocation( locationServer *types.DiscoveryServer, ) (*ServerBase, error) { errorMessage := "failed adding a location" // Initialize the base map if it is non-nil - if secure.BaseMap == nil { - secure.BaseMap = make(map[string]*ServerBase) + if server.BaseMap == nil { + server.BaseMap = make(map[string]*ServerBase) } // Add the location to the base map - base, exists := secure.BaseMap[locationServer.CountryCode] + base, exists := server.BaseMap[locationServer.CountryCode] if !exists || base == nil { // Create the base to be added to the map base = &ServerBase{} base.URL = locationServer.BaseURL - base.DisplayName = secure.DisplayName + base.DisplayName = server.DisplayName base.SupportContact = locationServer.SupportContact base.Type = "secure_internet" endpointsErr := base.InitializeEndpoints() @@ -118,37 +118,37 @@ func (secure *SecureInternetHomeServer) addLocation( } // Ensure it is in the map - secure.BaseMap[locationServer.CountryCode] = base + server.BaseMap[locationServer.CountryCode] = base return base, nil } // Initializes the home server and adds its own location -func (secure *SecureInternetHomeServer) init( +func (server *SecureInternetHomeServer) init( homeOrg *types.DiscoveryOrganization, homeLocation *types.DiscoveryServer, ) error { errorMessage := "failed initializing secure internet home server" - if secure.HomeOrganizationID != homeOrg.OrgId { + if server.HomeOrganizationID != homeOrg.OrgID { // New home organisation, clear everything - *secure = SecureInternetHomeServer{} + *server = SecureInternetHomeServer{} } // Make sure to set the organization ID - secure.HomeOrganizationID = homeOrg.OrgId - secure.DisplayName = homeOrg.DisplayName + server.HomeOrganizationID = homeOrg.OrgID + server.DisplayName = homeOrg.DisplayName // Make sure to set the authorization URL template - secure.AuthorizationTemplate = homeLocation.AuthenticationURLTemplate + server.AuthorizationTemplate = homeLocation.AuthenticationURLTemplate - base, baseErr := secure.addLocation(homeLocation) + base, baseErr := server.addLocation(homeLocation) if baseErr != nil { return types.NewWrappedError(errorMessage, baseErr) } // Make sure oauth contains our endpoints - secure.OAuth.Init(base.URL, base.Endpoints.API.V3.Authorization, base.Endpoints.API.V3.Token) + server.OAuth.Init(base.URL, base.Endpoints.API.V3.Authorization, base.Endpoints.API.V3.Token) return nil } diff --git a/internal/util/util_test.go b/internal/util/util_test.go index dbeec62..bb76752 100644 --- a/internal/util/util_test.go +++ b/internal/util/util_test.go @@ -3,10 +3,9 @@ package util import ( "bytes" "testing" - "time" ) -func Test_EnsureValidURL(t *testing.T) { +func TestEnsureValidURL(t *testing.T) { _, validErr := EnsureValidURL("%notvalid%") if validErr == nil { @@ -39,7 +38,7 @@ func Test_EnsureValidURL(t *testing.T) { } } -func Test_MakeRandomByteSlice(t *testing.T) { +func TestMakeRandomByteSlice(t *testing.T) { random, randomErr := MakeRandomByteSlice(32) if randomErr != nil { t.Fatalf("Got: %v, want: nil", randomErr) @@ -58,7 +57,7 @@ func Test_MakeRandomByteSlice(t *testing.T) { } } -func Test_WAYFEncode(t *testing.T) { +func TestWAYFEncode(t *testing.T) { // AuthTemplate returnTo := "127.0.0.1:8000/test123bla/#wow " @@ -70,7 +69,7 @@ func Test_WAYFEncode(t *testing.T) { } } -func Test_ReplaceWAYF(t *testing.T) { +func TestReplaceWAYF(t *testing.T) { // We expect url encoding but the spaces to be correctly replace with a + instead of a %20 // And we expect that the return to and org_id are correctly replaced replaced := ReplaceWAYF( @@ -112,7 +111,7 @@ func Test_ReplaceWAYF(t *testing.T) { } } -func Test_GetLanguageMatched(t *testing.T) { +func TestGetLanguageMatched(t *testing.T) { // exact match returned := GetLanguageMatched(map[string]string{"en": "test", "de": "test2"}, "en") if returned != "test" { diff --git a/internal/verify/verify.go b/internal/verify/verify.go index 2dd0472..6432619 100644 --- a/internal/verify/verify.go +++ b/internal/verify/verify.go @@ -7,7 +7,7 @@ import ( "github.com/jedisct1/go-minisign" ) -// Verify verifies the signature (.minisig file format) on signedJson. +// Verify verifies the signature (.minisig file format) on signedJSON. // // expectedFileName must be set to the file type to be verified, either "server_list.json" or "organization_list.json". // minSign must be set to the minimum UNIX timestamp (without milliseconds) for the file version. @@ -20,7 +20,7 @@ import ( // Verify is a wrapper around verifyWithKeys where allowedPublicKeys is set to the list from https://git.sr.ht/~eduvpn/disco.eduvpn.org#public-keys. func Verify( signatureFileContent string, - signedJson []byte, + signedJSON []byte, expectedFileName string, minSignTime uint64, forcePrehash bool, @@ -32,7 +32,7 @@ func Verify( } valid, err := verifyWithKeys( signatureFileContent, - signedJson, + signedJSON, expectedFileName, minSignTime, keyStrs, @@ -44,7 +44,7 @@ func Verify( return valid, nil } -// verifyWithKeys verifies the Minisign signature in signatureFileContent (minisig file format) over the server_list/organization_list JSON in signedJson. +// verifyWithKeys verifies the Minisign signature in signatureFileContent (minisig file format) over the server_list/organization_list JSON in signedJSON. // // Verification is performed using a matching key in allowedPublicKeys. // The signature is checked to be a Ed25519 Minisign (optionally Ed25519 Blake2b-512 prehashed, see forcePrehash) signature with a valid trusted comment. @@ -56,7 +56,7 @@ func Verify( // Note that every error path is wrapped in a custom type here because minisign does not return custom error types, they use errors.New func verifyWithKeys( signatureFileContent string, - signedJson []byte, + signedJSON []byte, filename string, minSignTime uint64, allowedPublicKeys []string, @@ -97,7 +97,7 @@ func verifyWithKeys( continue // Wrong key } - valid, err := key.Verify(signedJson, sig) + valid, err := key.Verify(signedJSON, sig) if !valid { return false, &VerifyInvalidSignatureError{Err: err} } diff --git a/internal/wireguard/wireguard.go b/internal/wireguard/wireguard.go index 0a1ba5f..bbb22e4 100644 --- a/internal/wireguard/wireguard.go +++ b/internal/wireguard/wireguard.go @@ -22,14 +22,14 @@ func GenerateKey() (wgtypes.Key, error) { // FIXME: Instead of doing a regex replace, decide if we should use a parser func ConfigAddKey(config string, key wgtypes.Key) string { - interface_section := "[Interface]" - interface_section_escaped := regexp.QuoteMeta(interface_section) + interfaceSection := "[Interface]" + InterfaceSectionEscaped := regexp.QuoteMeta(interfaceSection) // (?m) enables multi line mode // ^ match from beginning of line // $ match till end of line // So it matches [Interface] section exactly - interface_re := regexp.MustCompile(fmt.Sprintf("(?m)^%s$", interface_section_escaped)) - to_replace := fmt.Sprintf("%s\nPrivateKey = %s", interface_section, key.String()) - return interface_re.ReplaceAllString(config, to_replace) + InterfaceRe := regexp.MustCompile(fmt.Sprintf("(?m)^%s$", InterfaceSectionEscaped)) + toReplace := fmt.Sprintf("%s\nPrivateKey = %s", interfaceSection, key.String()) + return InterfaceRe.ReplaceAllString(config, toReplace) } diff --git a/types/error.go b/types/error.go index dc4b90e..fd56f3d 100644 --- a/types/error.go +++ b/types/error.go @@ -9,16 +9,16 @@ type ErrorLevel int8 const ( // All other errors, default - ERR_OTHER ErrorLevel = iota + ErrOther ErrorLevel = iota // The erorr is just here as additional info - ERR_INFO + ErrInfo // The error is just here as a warning - ERR_WARNING + ErrWarning // The error is fatal, the app cannot function - ERR_FATAL + ErrFatal ) type WrappedErrorMessage struct { @@ -94,5 +94,5 @@ func GetErrorLevel(err error) ErrorLevel { if errors.As(err, &wrappedErr) { return wrappedErr.Level } - return ERR_OTHER + return ErrOther } diff --git a/types/server.go b/types/server.go index e149b16..24db8f2 100644 --- a/types/server.go +++ b/types/server.go @@ -17,7 +17,7 @@ type DiscoveryOrganizations struct { type DiscoveryOrganization struct { DisplayName DiscoMapOrString `json:"display_name"` - OrgId string `json:"org_id"` + OrgID string `json:"org_id"` SecureInternetHome string `json:"secure_internet_home"` KeywordList DiscoMapOrString `json:"keyword_list"` } |
