-
Notifications
You must be signed in to change notification settings - Fork 311
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6667 from TheThingsNetwork/feature/ws-auth
Console protocol authentication and rate limiting
- Loading branch information
Showing
9 changed files
with
205 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
// Copyright © 2023 The Things Network Foundation, The Things Industries B.V. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package middleware | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"net/textproto" | ||
"strings" | ||
|
||
"go.thethings.network/lorawan-stack/v3/pkg/auth" | ||
) | ||
|
||
var ( | ||
protocolHeader = textproto.CanonicalMIMEHeaderKey("Sec-WebSocket-Protocol") | ||
authorizationHeader = textproto.CanonicalMIMEHeaderKey("Authorization") | ||
connectionHeader = textproto.CanonicalMIMEHeaderKey("Connection") | ||
upgradeHeader = textproto.CanonicalMIMEHeaderKey("Upgrade") | ||
) | ||
|
||
func isWebSocketRequest(r *http.Request) bool { | ||
h := r.Header | ||
return strings.EqualFold(h.Get(connectionHeader), "upgrade") && | ||
strings.EqualFold(h.Get(upgradeHeader), "websocket") | ||
} | ||
|
||
// ProtocolAuthentication returns a middleware that authenticates WebSocket requests using the subprotocol. | ||
// The subprotocol must be prefixed with the given prefix. | ||
// The token is extracted from the subprotocol and used to authenticate the request. | ||
// If the token is valid, the subprotocol is removed from the request. | ||
// If the token is invalid, the request is not authenticated. | ||
func ProtocolAuthentication(prefix string) func(http.Handler) http.Handler { | ||
prefixLen := len(prefix) | ||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
if !isWebSocketRequest(r) { | ||
next.ServeHTTP(w, r) | ||
return | ||
} | ||
if r.Header.Get(authorizationHeader) != "" { | ||
next.ServeHTTP(w, r) | ||
return | ||
} | ||
protocols := strings.Split(strings.TrimSpace(r.Header.Get(protocolHeader)), ",") | ||
newProtocols := make([]string, 0, len(protocols)) | ||
token := "" | ||
for _, protocol := range protocols { | ||
p := strings.TrimSpace(protocol) | ||
if len(p) >= prefixLen && strings.EqualFold(prefix, p[:prefixLen]) { | ||
token = p[prefixLen:] | ||
continue | ||
} | ||
newProtocols = append(newProtocols, p) | ||
} | ||
if _, _, _, err := auth.SplitToken(token); err == nil { | ||
if len(newProtocols) > 0 { | ||
r.Header.Set(protocolHeader, strings.Join(newProtocols, ",")) | ||
} else { | ||
r.Header.Del(protocolHeader) | ||
} | ||
r.Header.Set(authorizationHeader, fmt.Sprintf("Bearer %s", token)) | ||
} | ||
next.ServeHTTP(w, r) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
// Copyright © 2023 The Things Network Foundation, The Things Industries B.V. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// Package middleware implements the events middleware. | ||
package middleware |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// Copyright © 2023 The Things Network Foundation, The Things Industries B.V. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package events | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"go.thethings.network/lorawan-stack/v3/pkg/auth/rights" | ||
"go.thethings.network/lorawan-stack/v3/pkg/errors" | ||
"go.thethings.network/lorawan-stack/v3/pkg/ratelimit" | ||
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb" | ||
) | ||
|
||
var ( | ||
errUnknownCaller = errors.DefineInternal("unknown_caller", "unknown caller type `{type}`") | ||
errRateExceeded = errors.DefineResourceExhausted("rate_exceeded", "request rate exceeded") | ||
) | ||
|
||
func makeRateLimiter(ctx context.Context, limiter ratelimit.Interface) (func() error, error) { | ||
authInfo, err := rights.AuthInfo(ctx) | ||
if err != nil { | ||
return nil, err | ||
} | ||
resourceID := "" | ||
switch method := authInfo.AccessMethod.(type) { | ||
case *ttnpb.AuthInfoResponse_ApiKey: | ||
resourceID = fmt.Sprintf("api-key:%s", method.ApiKey.ApiKey.Id) | ||
case *ttnpb.AuthInfoResponse_OauthAccessToken: | ||
resourceID = fmt.Sprintf("access-token:%s", method.OauthAccessToken.Id) | ||
case *ttnpb.AuthInfoResponse_UserSession: | ||
resourceID = fmt.Sprintf("session-id:%s", method.UserSession.SessionId) | ||
// NOTE: *ttnpb.AuthInfoResponse_GatewayToken_ is intentionally left out. | ||
default: | ||
return nil, errUnknownCaller.WithAttributes("type", fmt.Sprintf("%T", authInfo.AccessMethod)) | ||
} | ||
resource := ratelimit.ConsoleEventsRequestResource(resourceID) | ||
return func() error { | ||
if limit, _ := limiter.RateLimit(resource); limit { | ||
return errRateExceeded.New() | ||
} | ||
return nil | ||
}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters