context.go 11.5 KB
Newer Older
1
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
2 3
// See License.txt for license information.

4
package web
5 6 7

import (
	"net/http"
8
	"path"
9
	"regexp"
10 11
	"strings"

Christopher Speller's avatar
Christopher Speller committed
12
	"github.com/mattermost/mattermost-server/app"
13
	"github.com/mattermost/mattermost-server/mlog"
Christopher Speller's avatar
Christopher Speller committed
14 15
	"github.com/mattermost/mattermost-server/model"
	"github.com/mattermost/mattermost-server/utils"
16 17 18
)

type Context struct {
Chris's avatar
Chris committed
19
	App           *app.App
20
	Log           *mlog.Logger
21
	Params        *Params
22 23
	Err           *model.AppError
	siteURLHeader string
24 25 26
}

func (c *Context) LogAudit(extraInfo string) {
27
	audit := &model.Audit{UserId: c.App.Session.UserId, IpAddress: c.App.IpAddress, Action: c.App.Path, ExtraInfo: extraInfo, SessionId: c.App.Session.Id}
28
	if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil {
29 30 31 32 33 34
		c.LogError(r.Err)
	}
}

func (c *Context) LogAuditWithUserId(userId, extraInfo string) {

35 36
	if len(c.App.Session.UserId) > 0 {
		extraInfo = strings.TrimSpace(extraInfo + " session_user=" + c.App.Session.UserId)
37 38
	}

39
	audit := &model.Audit{UserId: userId, IpAddress: c.App.IpAddress, Action: c.App.Path, ExtraInfo: extraInfo, SessionId: c.App.Session.Id}
40
	if r := <-c.App.Srv.Store.Audit().Save(audit); r.Err != nil {
41 42 43 44 45
		c.LogError(r.Err)
	}
}

func (c *Context) LogError(err *model.AppError) {
46 47
	// Filter out 404s, endless reconnects and browser compatibility errors
	if err.StatusCode == http.StatusNotFound ||
48
		(c.App.Path == "/api/v3/users/websocket" && err.StatusCode == http.StatusUnauthorized) ||
49
		err.Id == "web.check_browser_compatibility.app_error" {
50 51
		c.LogDebug(err)
	} else {
52 53 54 55 56 57
		c.Log.Error(
			err.SystemMessage(utils.TDefault),
			mlog.String("err_where", err.Where),
			mlog.Int("http_code", err.StatusCode),
			mlog.String("err_details", err.DetailedError),
		)
58 59 60
	}
}

61
func (c *Context) LogInfo(err *model.AppError) {
62 63 64 65
	// Filter out 401s
	if err.StatusCode == http.StatusUnauthorized {
		c.LogDebug(err)
	} else {
66 67 68 69 70 71
		c.Log.Info(
			err.SystemMessage(utils.TDefault),
			mlog.String("err_where", err.Where),
			mlog.Int("http_code", err.StatusCode),
			mlog.String("err_details", err.DetailedError),
		)
72
	}
73 74
}

75
func (c *Context) LogDebug(err *model.AppError) {
76 77 78 79 80 81
	c.Log.Debug(
		err.SystemMessage(utils.TDefault),
		mlog.String("err_where", err.Where),
		mlog.Int("http_code", err.StatusCode),
		mlog.String("err_details", err.DetailedError),
	)
82 83 84
}

func (c *Context) IsSystemAdmin() bool {
85
	return c.App.SessionHasPermissionTo(c.App.Session, model.PERMISSION_MANAGE_SYSTEM)
86 87 88
}

func (c *Context) SessionRequired() {
89
	if !*c.App.Config().ServiceSettings.EnableUserAccessTokens && c.App.Session.Props[model.SESSION_PROP_TYPE] == model.SESSION_TYPE_USER_ACCESS_TOKEN {
90 91 92 93
		c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserAccessToken", http.StatusUnauthorized)
		return
	}

94
	if len(c.App.Session.UserId) == 0 {
95
		c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "UserRequired", http.StatusUnauthorized)
96 97 98 99 100 101
		return
	}
}

func (c *Context) MfaRequired() {
	// Must be licensed for MFA and have it configured for enforcement
102
	if license := c.App.License(); license == nil || !*license.Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication {
103 104 105 106
		return
	}

	// OAuth integrations are excepted
107
	if c.App.Session.IsOAuth {
108 109 110
		return
	}

111
	if user, err := c.App.GetUser(c.App.Session.UserId); err != nil {
112
		c.Err = model.NewAppError("", "api.context.session_expired.app_error", nil, "MfaRequired", http.StatusUnauthorized)
113 114 115 116 117 118 119 120 121
		return
	} else {
		// Only required for email and ldap accounts
		if user.AuthService != "" &&
			user.AuthService != model.USER_AUTH_SERVICE_EMAIL &&
			user.AuthService != model.USER_AUTH_SERVICE_LDAP {
			return
		}

122
		// Special case to let user get themself
123
		subpath, _ := utils.GetSubpathFromConfig(c.App.Config())
124
		if c.App.Path == path.Join(subpath, "/api/v4/users/me") {
125 126 127
			return
		}

128
		if !user.MfaActive {
129
			c.Err = model.NewAppError("", "api.context.mfa_required.app_error", nil, "MfaRequired", http.StatusForbidden)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
			return
		}
	}
}

func (c *Context) RemoveSessionCookie(w http.ResponseWriter, r *http.Request) {
	cookie := &http.Cookie{
		Name:     model.SESSION_COOKIE_TOKEN,
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}

	http.SetCookie(w, cookie)
}

func (c *Context) SetInvalidParam(parameter string) {
	c.Err = NewInvalidParamError(parameter)
}

func (c *Context) SetInvalidUrlParam(parameter string) {
	c.Err = NewInvalidUrlParamError(parameter)
}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
func (c *Context) HandleEtag(etag string, routeName string, w http.ResponseWriter, r *http.Request) bool {
	metrics := c.App.Metrics
	if et := r.Header.Get(model.HEADER_ETAG_CLIENT); len(etag) > 0 {
		if et == etag {
			w.Header().Set(model.HEADER_ETAG_SERVER, etag)
			w.WriteHeader(http.StatusNotModified)
			if metrics != nil {
				metrics.IncrementEtagHitCounter(routeName)
			}
			return true
		}
	}

	if metrics != nil {
		metrics.IncrementEtagMissCounter(routeName)
	}

	return false
}

175
func NewInvalidParamError(parameter string) *model.AppError {
176
	err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest)
177 178 179
	return err
}
func NewInvalidUrlParamError(parameter string) *model.AppError {
180
	err := model.NewAppError("Context", "api.context.invalid_url_param.app_error", map[string]interface{}{"Name": parameter}, "", http.StatusBadRequest)
181 182 183 184
	return err
}

func (c *Context) SetPermissionError(permission *model.Permission) {
185
	c.Err = c.App.MakePermissionError(permission)
186 187
}

188 189
func (c *Context) SetSiteURLHeader(url string) {
	c.siteURLHeader = strings.TrimRight(url, "/")
190 191
}

192 193
func (c *Context) GetSiteURLHeader() string {
	return c.siteURLHeader
194 195 196 197 198 199 200
}

func (c *Context) RequireUserId() *Context {
	if c.Err != nil {
		return c
	}

201
	if c.Params.UserId == model.ME {
202
		c.Params.UserId = c.App.Session.UserId
203 204
	}

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	if len(c.Params.UserId) != 26 {
		c.SetInvalidUrlParam("user_id")
	}
	return c
}

func (c *Context) RequireTeamId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.TeamId) != 26 {
		c.SetInvalidUrlParam("team_id")
	}
	return c
}

222 223 224 225 226
func (c *Context) RequireInviteId() *Context {
	if c.Err != nil {
		return c
	}

227
	if len(c.Params.InviteId) == 0 {
228 229 230 231 232
		c.SetInvalidUrlParam("invite_id")
	}
	return c
}

233 234 235 236 237 238 239 240 241 242 243
func (c *Context) RequireTokenId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.TokenId) != 26 {
		c.SetInvalidUrlParam("token_id")
	}
	return c
}

244 245 246 247 248 249 250 251 252 253
func (c *Context) RequireChannelId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.ChannelId) != 26 {
		c.SetInvalidUrlParam("channel_id")
	}
	return c
}
254

255 256 257 258 259
func (c *Context) RequireUsername() *Context {
	if c.Err != nil {
		return c
	}

260 261
	if !model.IsValidUsername(c.Params.Username) {
		c.SetInvalidParam("username")
262 263 264 265 266
	}

	return c
}

267 268 269 270 271 272 273 274 275 276 277
func (c *Context) RequirePostId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.PostId) != 26 {
		c.SetInvalidUrlParam("post_id")
	}
	return c
}

278 279 280 281 282 283 284 285 286 287 288
func (c *Context) RequireAppId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.AppId) != 26 {
		c.SetInvalidUrlParam("app_id")
	}
	return c
}

289 290 291 292 293 294 295 296 297 298 299 300
func (c *Context) RequireFileId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.FileId) != 26 {
		c.SetInvalidUrlParam("file_id")
	}

	return c
}

301 302 303 304 305 306 307 308 309 310 311 312
func (c *Context) RequireFilename() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.Filename) == 0 {
		c.SetInvalidUrlParam("filename")
	}

	return c
}

313 314 315 316 317 318 319 320 321 322 323 324
func (c *Context) RequirePluginId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.PluginId) == 0 {
		c.SetInvalidUrlParam("plugin_id")
	}

	return c
}

325 326 327 328 329 330 331 332 333 334 335
func (c *Context) RequireReportId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.ReportId) != 26 {
		c.SetInvalidUrlParam("report_id")
	}
	return c
}

336 337 338 339 340 341 342 343 344 345 346
func (c *Context) RequireEmojiId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.EmojiId) != 26 {
		c.SetInvalidUrlParam("emoji_id")
	}
	return c
}

347 348 349 350 351
func (c *Context) RequireTeamName() *Context {
	if c.Err != nil {
		return c
	}

352
	if !model.IsValidTeamName(c.Params.TeamName) {
353 354 355 356 357 358 359 360 361 362 363 364 365
		c.SetInvalidUrlParam("team_name")
	}

	return c
}

func (c *Context) RequireChannelName() *Context {
	if c.Err != nil {
		return c
	}

	if !model.IsValidChannelIdentifier(c.Params.ChannelName) {
		c.SetInvalidUrlParam("channel_name")
366
	}
367 368 369 370

	return c
}

371 372 373 374 375
func (c *Context) RequireEmail() *Context {
	if c.Err != nil {
		return c
	}

376
	if !model.IsValidEmail(c.Params.Email) {
377 378 379 380 381
		c.SetInvalidUrlParam("email")
	}

	return c
}
382 383 384 385 386 387

func (c *Context) RequireCategory() *Context {
	if c.Err != nil {
		return c
	}

388
	if !model.IsValidAlphaNumHyphenUnderscore(c.Params.Category, true) {
389 390 391 392 393 394
		c.SetInvalidUrlParam("category")
	}

	return c
}

395 396 397 398 399 400 401 402 403 404 405 406
func (c *Context) RequireService() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.Service) == 0 {
		c.SetInvalidUrlParam("service")
	}

	return c
}

407 408 409 410 411
func (c *Context) RequirePreferenceName() *Context {
	if c.Err != nil {
		return c
	}

412
	if !model.IsValidAlphaNumHyphenUnderscore(c.Params.PreferenceName, true) {
413 414 415 416 417
		c.SetInvalidUrlParam("preference_name")
	}

	return c
}
418

419 420 421 422 423
func (c *Context) RequireEmojiName() *Context {
	if c.Err != nil {
		return c
	}

424 425
	validName := regexp.MustCompile(`^[a-zA-Z0-9\-\+_]+$`)

426
	if len(c.Params.EmojiName) == 0 || len(c.Params.EmojiName) > model.EMOJI_NAME_MAX_LENGTH || !validName.MatchString(c.Params.EmojiName) {
427 428 429 430 431 432
		c.SetInvalidUrlParam("emoji_name")
	}

	return c
}

433 434 435 436 437 438 439 440 441 442 443
func (c *Context) RequireHookId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.HookId) != 26 {
		c.SetInvalidUrlParam("hook_id")
	}

	return c
}
444 445 446 447 448 449 450 451 452 453 454

func (c *Context) RequireCommandId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.CommandId) != 26 {
		c.SetInvalidUrlParam("command_id")
	}
	return c
}
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

func (c *Context) RequireJobId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.JobId) != 26 {
		c.SetInvalidUrlParam("job_id")
	}
	return c
}

func (c *Context) RequireJobType() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.JobType) == 0 || len(c.Params.JobType) > 32 {
		c.SetInvalidUrlParam("job_type")
	}
	return c
}
477 478 479 480 481 482 483 484 485 486 487

func (c *Context) RequireActionId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.ActionId) != 26 {
		c.SetInvalidUrlParam("action_id")
	}
	return c
}
488 489 490 491 492 493 494 495 496 497 498 499

func (c *Context) RequireRoleId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.RoleId) != 26 {
		c.SetInvalidUrlParam("role_id")
	}
	return c
}

500 501 502 503 504 505 506 507 508 509 510
func (c *Context) RequireSchemeId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.SchemeId) != 26 {
		c.SetInvalidUrlParam("scheme_id")
	}
	return c
}

511 512 513 514 515 516 517 518 519 520 521
func (c *Context) RequireRoleName() *Context {
	if c.Err != nil {
		return c
	}

	if !model.IsValidRoleName(c.Params.RoleName) {
		c.SetInvalidUrlParam("role_name")
	}

	return c
}
Martin Kraft's avatar
Martin Kraft committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

func (c *Context) RequireGroupId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.GroupId) != 26 {
		c.SetInvalidUrlParam("group_id")
	}
	return c
}

func (c *Context) RequireRemoteId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.RemoteId) == 0 {
		c.SetInvalidUrlParam("remote_id")
	}
	return c
}

func (c *Context) RequireSyncableId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.SyncableId) != 26 {
		c.SetInvalidUrlParam("syncable_id")
	}
	return c
}

func (c *Context) RequireSyncableType() *Context {
	if c.Err != nil {
		return c
	}

	if c.Params.SyncableType != model.GroupSyncableTypeTeam && c.Params.SyncableType != model.GroupSyncableTypeChannel {
		c.SetInvalidUrlParam("syncable_type")
	}
	return c
}
566 567 568 569 570 571 572 573 574 575 576

func (c *Context) RequireBotUserId() *Context {
	if c.Err != nil {
		return c
	}

	if len(c.Params.BotUserId) != 26 {
		c.SetInvalidUrlParam("bot_user_id")
	}
	return c
}